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

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

本文关键字:类型 于组 underscorejs 获取 使用      更新时间:2023-09-26

我正在尝试获取所有类型的总数和下面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),以及类型1(TypeOneTotal:90)和类型2(TypeTwoTotal:120)的单独计数。

所以我期待以下数组:

    var json = { 
                "AllTypeTotal":210, 
                "TypeOneTotal":90,
                "TypeTwoTotal":120
               }

可以使用Undercore的reduce或原生数组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 } );

我可以帮助您使用lodash,它是下划线的超集,在性能和一致性方面比下划线好得多(请参阅lodash与下划线)。

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