I am trying to create a map with unique key elements from an JSON array and set the value to the khey with a total of item property, qty for each objects with the same id. There are total 5 objects in the array. The objects with id: equals to 123 should add up to 40 and objects with id: equals 456 should add up to 90 but instead id:456 adds up to 130.
I have put together a fiddle for reference https://jsfiddle.net/5jdhatq2/2/
And here is the code
id: 123,
qty: 20
},
{
id: 456,
qty: 30
},
{
id: 123,
qty: 20
},
{
id: 456,
qty: 30
},
{
id: 456,
qty: 30
}
]
var priceMap = new Map();
var dataArray = [123, 456];
var qty = 0;
for (var i = 0; i < dataArray.length; i++) {
for (var j = 0; j < data.length; j++) {
if (dataArray[i] == data[j].id) {
var qty = qty + data[j].qty;
priceMap.set(dataArray[i], qty);
}
}
}
console.log(priceMap.get(123), priceMap.get(456))
//expected outcome -- priceMap.get(123) -> 40 and priceMap.get(456) -> 90
Cant figure out what I am doing wrong here