我有这样的JSON:
[
{
platformId: 1,
payout: 15,
numOfPeople: 4
},
{
platformId: 1,
payout: 12,
numOfPeople: 3
},
{
platformId: 2,
payout: 6,
numOfPeople: 5
},
{
platformId: 2,
payout: 10,
numOfPeople: 1
},
]
我希望按platformId
与payout
和numOfPeople
之和进行分组。
即。结果我想要这样的JSON:
[
"1": {
payout: 27,
numOfPeople: 7
},
"2": {
payout: 16,
numOfPeople: 6
}
]
我尝试使用underscore.js
的{{1}}方法,并且它组合得很好,但我如何才能获得上面演示的对象属性值的SUM?
答案 0 :(得分:18)
这是解决此类问题的Lodash解决方案。它与Underscore类似,但具有一些更高级的功能。
const data = [{
platformId: 1,
payout: 15,
numOfPeople: 4
},
{
platformId: 1,
payout: 12,
numOfPeople: 3
},
{
platformId: 2,
payout: 6,
numOfPeople: 5
},
{
platformId: 2,
payout: 10,
numOfPeople: 1
},
];
const ans = _(data)
.groupBy('platformId')
.map((platform, id) => ({
platformId: id,
payout: _.sumBy(platform, 'payout'),
numOfPeople: _.sumBy(platform, 'numOfPeople')
}))
.value()
console.log(ans);
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
答案 1 :(得分:12)
我尝试以功能方式执行此操作,结果就像这样
console.log(_.chain(data)
.groupBy("platformId")
.map(function(value, key) {
return [key, _.reduce(value, function(result, currentObject) {
return {
payout: result.payout + currentObject.payout,
numOfPeople: result.numOfPeople + currentObject.numOfPeople
}
}, {
payout: 0,
numOfPeople: 0
})];
})
.object()
.value());
答案 2 :(得分:6)
您可以在没有下划线的情况下执行此操作:
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
},{})
但是为什么你想要一个带数字键的对象?您可以将其转换回集合:
var toCollection = function(obj) {
return Object.keys(obj)
.sort(function(x, y){return +x - +y})
.map(function(k){return obj[k]})
}
toCollection(result)
请注意,对象是变异的,因此如果要维护原始数据,可以先将它们克隆。
答案 3 :(得分:3)
A(在我看来)使用underscore.js的很好的功能方式:
var sum = function(t, n) { return t + n; };
_.mapObject(
_.groupBy(data, 'platformId'),
function(values, platformId) {
return {
payout: _.reduce(_.pluck(values, 'payout'), sum, 0),
numOfPeople: _.reduce(_.pluck(values, 'numOfPeople'), sum, 0)
};
}
);
答案 4 :(得分:1)
本着lodash的眼光
_.map(_.groupBy(your_list, 'group_by'), (o,idx) => { return { id: idx, summed: _.sumBy(o,'sum_me') }})
答案 5 :(得分:-1)
//Input
[{
"platformId": 1,
"payout": 15,
"numOfPeople": 4
}, {
"platformId": 1,
"payout": 12,
"numOfPeople": 3
}, {
"platformId": 2,
"payout": 6,
"numOfPeople": 5
}, {
"platformId": 2,
"payout": 10,
"numOfPeople": 1
}]
//Output
{
"1": {
"payout": 43,
"numOfPeople": 13
},
"2": {
"payout": 43,
"numOfPeople": 13
}
}
// Code
output = _.reduce(input, function(acc, val, key) {
acc[val.platformId] = {
payout: _.sum(a, 'payout'),
numOfPeople: _.sum(a, 'numOfPeople')
};
return acc;
}, {});