Javascript 使用下划线获取所有类型的总计数和基于组(类型)的计数

Javascript 使用下划线获取所有类型的总计数和基于组(类型)的计数,javascript,underscore.js,Javascript,Underscore.js,我试图获得所有类型的总计数和低于json数组的基于组的计数 var json = {"items":[ {"type":1,"count":10}, {"type":1,"count":10}, {"type":2,"count":20}, {"type":1,"count":30},

我试图获得所有类型的总计数和低于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
               }
我可以帮助您,这是下划线的超集,在性能和一致性方面比下划线要好得多(请参阅)


可以使用下划线或本机。下面是一个下划线解决方案:

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 } );
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 } );