I have a json array as follows
var arrayVal = [{id:"1",name:"A", sAge: 20, eAge:30},{id:"2",name:"B", sAge: 30, eAge:50},{id:"2",name:"B", sAge: 20, eAge:40},{id:"3",name:"C", Aage: 20, eAge:50},{id:"4",name:"D", sAge: 10, eAge:30}];
I want to take difference of sAge and eAge of each id and sum the final value if there are multiple diff values of same id. For that I have the following code
const ages = array.reduce((a, {id, sAge, eAge}) => (a[id] = (a[id] || 0) + eAge - sAge, a), {});
console.log(ages);
output of the above code snippet is as follows
{
"1": 20,
"2": 50,
"3": 20,
"4": 10
}
But If I want to obtain an array as follows after using reduce(), how can I achieve that?
[{id:"1",name:"A", hours:"20"},{id:"2",name:"B", hours:"50"},{id:"3",name:"C", hours:"20"},{id:"5",name:"D", hours:"10"}]