I have this array, and i want to get the sum amount of each Order.item
[
{"OrderReceiverId":"6698eea782e24cc9d42eab7f",
"Order":{
"CustomerId":"669aa55079cce2e96f9a7e69",
"CustomerName":"Erigbemi",
"Date":"2024/07/19",
"TrackingId":"43035",
"Status":"Processing",
"Amount":{"$numberInt":"25000"},
"Item":"Orange"
}
}, {"OrderReceiverId":"6698eea782e24cc9d42eab7f",
"Order":{
"CustomerId":"669aa55079cce2e96f96t77",
"CustomerName":"James",
"Date":"2024/07/19",
"TrackingId":"42335",
"Status":"Processing",
"Amount":{"$numberInt":"15000"},
"Item":"Tomatoes"
}, {"OrderReceiverId":"6698eea782e24cc9d42eab7f",
"Order":{
"CustomerId":"669aa55079cce2e96f9a7e69",
"CustomerName":"Erigbemi",
"Date":"2024/07/19",
"TrackingId":"22235",
"Status":"Processing",
"Amount":{"$numberInt":"15000"},
"Item":"Tomatoes"
}
]
How do i get the total of each "Item", something like this
"Rice": 30000
"Tomatoes": 15000
i tried this
let itm = {};
sellingInfo.forEach(order => {
const item = order.Order.Item;
const amt = order.Order.Amount;
if(!itm[item]){
itm[item] = amt;
}
itm[item] += amt;
})
res.json(itm);
But i seemd to be getting the wrong out put, this is what I get
{
"Orange": 50000,
"Tomatoes": 45000
}
2
Answers
you may use
Array.reduce()
methodYou can use reduce method to accumulate the total amounts for each item: