From the object below, I wanted to sum up certain properties (fare+tax and com+agency) by their key group (1345, 2353) and updated it in the current array object.
var details = [{ 1345:[
{route: 34, fare: 45, tax: 46, date: 46, com: 45, agency: 24, totalCost: 0, totalFee: 0}],
2353: [
{route: 32, fare: 45, tax: 45, date: 56, com: 34, agency: 52, totalCost: 0, totalFee: 0},
{route: 42, fare: 34, tax: 64, date: 34, com: 56, agency: 34, totalCost: 0, totalFee: 0}
]}
]
expected output: updated details (totalCost and totalFee)
1345:
{ route: 34, fare: 45, .... totalCost: 91, totalFee: 69 }
2353:
{ route: 32, fare: 45, ... totalCost: 188, totalFee: 90 },
{ route: 42, fare: 34, ... totalCost: 188, totalFee: 176 }
totalCost = fare + tax and totalFee = com + agency
I tried to simplified the array objects and convert by using Object.entries(details[0]), then reduce to sum up the target properties.
Object.entries(details[0]).reduce((acc, curr) => (acc = acc + curr["fare"]+curr["tax"]), 0);
However, NaN was returned.
Would appreciate if anyone could show me how I can loop through each key group and sum up the target values and update it (totalCost and totalFee).
Object.valuesinstead ofObject.entries, and also you don't need to assign a new value toacc.totalFeeon 2353 is wrong (34 + 52 + 56 + 34) !== 90