GROUP BY和点心使用下划线/ Lodash [英] Group By and Sum using Underscore/Lodash
问题描述
我有JSON是这样的:
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
},
]
和我想集团是由<$ C $ C> platformId 与派息
和 numOfPeople <总和/ code>。
And I want to Group it by platformId
with sum of payout
and numOfPeople
.
即。在结果我想JSON是这样的:
I.e. in result I want JSON like this:
[
"1": {
payout: 27,
numOfPeople: 7
},
"2": {
payout: 16,
numOfPeople: 6
}
]
我试图用 underscore.js
的 _。GROUPBY
方法,并且它团体罚款,但如何我可以得到对象的属性值的总和就像我上面证明?
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?
推荐答案
可以做到这一点,没有下划线:
You can do this without Underscore:
var result = data.reduce(function(acc, x) {
var id = acc[x.platformId]
if (id) {
id.payout += x.payout
id.numOfPeople += x.numOfPeople
} else {
acc[x.platformId] = x
delete x.platformId
}
return acc
},{})
但是,为什么你想用数字键的对象?你可以将其转换回一个集合:
But why would you want an object with numeric keys? You could convert it back to a collection:
var toCollection = function(obj) {
return Object.keys(obj)
.sort(function(x, y){return +x - +y})
.map(function(k){return obj[k]})
}
toCollection(result)
注意,对象都发生突变,所以你可能他们先克隆,如果你想保持原来的数据。
Note that objects are mutated, so you may to clone them first if you want to maintain the original data.
这篇关于GROUP BY和点心使用下划线/ Lodash的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!