我试图得到所有类型的总数和基于组的以下json数组计数。
var json = {"items":[
{"type":1,"count":10},
{"type":1,"count":10},
{"type":2,"count":20},
{"type":1,"count":30},
{"type":1,"count":40},
{"type":2,"count":100}
]
}我想得到所有类型的总数(AllTypeTotal:210)和type1(TypeOneTotal:90)和type2(TypeTwoTotal:120)的单独计数。
因此,我期待以下数组:
var json = {
"AllTypeTotal":210,
"TypeOneTotal":90,
"TypeTwoTotal":120
}发布于 2016-01-05 23:18:36
它可以使用下划线的reduce或本机array.reduce来完成。下面是一个下划线解决方案:
var result = _.reduce(json.items, function(memo, item){
// build the correct key
var key = 'Type' + item.type + 'Total';
// update the total
memo.AllTypeTotal += item.count;
// update the type total
memo[key] = (memo[key] | 0) + item.count;
return memo;
}, { AllTypeTotal: 0 } );发布于 2016-01-05 12:06:29
我可以帮助您使用房客,它是一个下划线的超集,在性能和一致性方面要比下划线好得多(参见下划线与下划线)。
var uniqTypes = _.pluck(_.uniq(json.items, "type"), "type");
var result = {};
uniqTypes.forEach(function(typeName){
result["type"+typeName+"total"] = 0;
_.map(data.items, function(item){
if(item.type === typeName)
result["type"+typeName+"total"] += item.count;
});
});https://stackoverflow.com/questions/34610746
复制相似问题