gpt4 book ai didi

javascript - 如果 hashMap 具有相同的键名称,如何获取对象数组中的所有值

转载 作者:行者123 更新时间:2023-12-03 00:39:01 26 4
gpt4 key购买 nike

我有一个 JSON 结构和代码,如下所示:

const villages = 
{
"lossesOccured":
[
{
"type": "destroyed",
"affectedOn": "humans",
"quantity": 120,
"reliefFund": 100000,
"location": {
"district": "thanjavur",
"villageName": "madukkur",
"pincode": "614903"
}
},
{
"type": "physicalDamage",
"affectedOn": "humans",
"quantity": 250,
"reliefFund": 50000,
"location": {
"district": "thanjavur",
"villageName": "madukkur",
"pincode": "614903"
}
}
]
}

const losses = villages.lossesOccured

const myMap = new Map()
const humanMap = new Map()

losses.forEach((data,index) => {
var keys = data.affectedOn
var objJSON = new Object();
for (i = 0; i < keys.length; i++) {
objJSON[keys] = data;
}
myMap.set(objJSON,data)
});

function extactLosses(){
myMap.forEach(loss => {
if(loss.affectedOn === "humans"){
humanMap.set(loss.affectedOn,[loss])
}

for (var [key, value] of humanMap) {
console.log(key , value);
}

从上面的代码来看,由于许多元素中存在相同的键名称(affectedOn),因此map消除了所有重复项并在输出中仅打印一个。有没有一种方法可以将键打印为字符串,将值打印为对象数组,而不消除具有相同键名称的对象。提前致谢。

输出: Map

预期输出 Expected

最佳答案

您似乎只想过滤 LossOccurred 数组以提取人类损失的数组。

const villages = 
{
"lossesOccured":
[
{
"type": "destroyed",
"affectedOn": "humans",
"quantity": 120,
"reliefFund": 100000,
"location": {
"district": "thanjavur",
"villageName": "madukkur",
"pincode": "614903"
}
},
{
"type": "physicalDamage",
"affectedOn": "humans",
"quantity": 250,
"reliefFund": 50000,
"location": {
"district": "thanjavur",
"villageName": "madukkur",
"pincode": "614903"
}
},
{
"type": "physicalDamage",
"affectedOn": "NOT humans",
"quantity": 250,
"reliefFund": 50000,
"location": {
"district": "thanjavur",
"villageName": "madukkur",
"pincode": "614903"
}
}
]
};

const humanLosses = villages.lossesOccured.filter(loss => loss.affectedOn == 'humans');

console.log(humanLosses);

关于javascript - 如果 hashMap 具有相同的键名称,如何获取对象数组中的所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53539440/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com