I have a JSON structure and code like below :
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);
}
From the above code,since there are same key names(affectedOn) in many elements, map eliminates all duplicates and prints only one in the output. Is there a way to print the key as string and value as array of objects without eliminating the ones with the same key name. Thanks in advance.
It seems like you just want to filter the lossesOccurred array to pull out the ones that were human losses.
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.