There is nice Array method reduce()
to get one value from the Array. Example:
JavaScript
x
4
1
[0,1,2,3,4].reduce(function(previousValue, currentValue, index, array){
2
return previousValue + currentValue;
3
});
4
What is the best way to achieve the same with objects? I’d like to do this:
JavaScript
1
8
1
{
2
a: {value:1},
3
b: {value:2},
4
c: {value:3}
5
}.reduce(function(previous, current, index, array){
6
return previous.value + current.value;
7
});
8
However, Object does not seem to have any reduce()
method implemented.
Advertisement
Answer
What you actually want in this case are the Object.values
. Here is a concise ES6 implementation with that in mind:
JavaScript
1
10
10
1
const add = {
2
a: {value:1},
3
b: {value:2},
4
c: {value:3}
5
}
6
7
const total = Object.values(add).reduce((t, {value}) => t + value, 0)
8
9
console.log(total) // 6
10
or simply:
JavaScript
1
10
10
1
const add = {
2
a: 1,
3
b: 2,
4
c: 3
5
}
6
7
const total = Object.values(add).reduce((t, n) => t + n)
8
9
console.log(total) // 6
10