Javascript reduce() on Object
What you actually want in this case are the Object.values
. Here is a concise ES6 implementation with that in mind:
const add = {
a: {value:1},
b: {value:2},
c: {value:3}
}
const total = Object.values(add).reduce((t, {value}) => t + value, 0)
console.log(total) // 6
or simply:
const add = {
a: 1,
b: 2,
c: 3
}
const total = Object.values(add).reduce((t, n) => t + n)
console.log(total) // 6
One option would be to reduce
the keys()
:
var o = {
a: {value:1},
b: {value:2},
c: {value:3}
};
Object.keys(o).reduce(function (previous, key) {
return previous + o[key].value;
}, 0);
With this, you'll want to specify an initial value or the 1st round will be 'a' + 2
.
If you want the result as an Object ({ value: ... }
), you'll have to initialize and return the object each time:
Object.keys(o).reduce(function (previous, key) {
previous.value += o[key].value;
return previous;
}, { value: 0 });