我具有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消除了所有重复项,并且在输出中仅输出一个。 有没有一种方法可以将键以字符串和值的形式显示为对象数组,而不必消除具有相同键名的键。 预先感谢。
答案 0 :(得分:1)
似乎您只想过滤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);