I have an array of objects like so:
[{state: CA, value: 1}, {state: CA, value: 1}, {state: NY, value: 10}]
I would like the final result to be an object that contains the aggregates of the value for the same states:
{CA: 2, NY: 10}
I have this code below to do that:
let arr = [{state: 'CA', value: 1}, {state: 'CA', value: 1}, {state: 'NY', value: 10}];
let finalObj = {};
arr.map(function(item) {
let state = item.state;
if (!finalObj[state]) {
finalObj[state] = item.value;
}else {
finalObj[state] += item.value;
}
});
console.log(finalObj);
Is there a better way to do this rather than having those if and else checks inside of the map function?