使用 underscorejs 获取所有类型的总数和基于组(类型)的计数

get total count of all types and group(type) based count using underscorejs

我正在尝试获取 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
               }

我可以帮你 lodash which is a superset of underscore and much better than underscore when it comes to performance and consistency (see lodash vs underscore).

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

可以使用 Underscore 的 reduce or the native 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 } );