I have JSON like this:
[
{
platformId: 1,
payout: 15,
numOfPeople: 4
},
{
platformId: 1,
payout: 12,
numOfPeople: 3
},
{
platformId: 2,
payout: 6,
numOfPeople: 5
},
{
platformId: 2,
payout: 10,
numOfPeople: 1
},
]
And I want to Group it by platformId
with sum of payout
and numOfPeople
.
I.e. in result I want JSON like this:
[
"1": {
payout: 27,
numOfPeople: 7
},
"2": {
payout: 16,
numOfPeople: 6
}
]
I tried to use underscore.js
's _.groupBy
method, and it groups fine, but how I can get the SUM of objects properties values like I demonstrated above?
A (in my opinion) nice functional way using underscore.js:
I tried to do this in the functional way, and the result was like this
You can do this without Underscore:
But why would you want an object with numeric keys? You could convert it back to a collection:
Note that objects are mutated, so you may to clone them first if you want to maintain the original data.
Here's a Lodash solution to this kind of problem. It's similar to Underscore, but with some more advanced features.