So I have an object that I need to sum a nested value for all the objects. My object looks like
const json = [
{
"other_sum": "1",
"summary": {
"calculations": {
"time": 10,
"unit": 25
},
"updated": "2020-06-05"
}
},
{
"other_sum": "1",
"summary": {
"calculations": {
"time": 20,
"unit": 5
},
"updated": "2020-06-05"
}
},
{
"other_sum": "1",
"summary": {
"calculations": {
"time": 5,
"unit": 15
},
"updated": "2020-06-05"
}
},
];
I need to sum all the "unit" values
I've been trying to use .reduce for this but it only works when I have 2 items in my object, onces I get a 3rd I get an error.
The rest of my code is the following:
const r = json.reduce((a, b) => a.summary.calculations.unit + b.summary.calculations.unit);
console.log(r);
Not really sure what I'm doing wrong atm.