I want to total all same ID and assign a specific key
var ingredArray= [{"inventory_id":1,"pergram":222},{"inventory_id":1,"pergram":33},{"inventory_id":2,"pergram":424},{"inventory_id":2,"pergram":22},{"inventory_id":3,"pergram":400},{"inventory_id":5,"pergram":200}]
let deduction={};
ingredArray.forEach(function (item) {
if (deduction.hasOwnProperty(item.inventory_id)) {
deduction[item.inventory_id] = deduction[item.inventory_id] + parseFloat(item.pergram);
} else {
deduction[item.inventory_id] = parseFloat(item.pergram);
}
});
console.log(deduction);
this is the result of my code
{1: 255, 2: 446, 3: 400, 5: 200}
I want to achieve
{"inventory_id":1,"pergram":255},{"inventory_id":2,"pergram":446},{"inventory_id":3,"pergram":400},{"inventory_id":5,"pergram":200}
ingredArrayand the final result that you want. As for yourdeductionvs the final result, that's not possible in a dictionary, it should have a properkeyand avalue. What you want as the final result is a sort of an array, and it looks exactly the same asingredArray