Javascript reduce() on Object
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 });
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
ES6 implementation: Object.entries()
const o = { a: {value: 1}, b: {value: 2}, c: {value: 3}};const total = Object.entries(o).reduce(function (total, pair) { const [key, value] = pair; return total + value;}, 0);