【问题标题】:Filter data in Jquery array and count by key过滤Jquery数组中的数据并按键计数
【发布时间】:2021-05-08 19:20:29
【问题描述】:
var newly = [
                {"id":"15","cm_id":"31","name":"nims","total":1},
                {"id":"15","cm_id":"61","name":"bims forum",,"total":3},
                {"id":"80","cm_id":"198","name":"rims for topic",,"total":2}
                ];

我想按 id 过滤上面的数组过滤器并找到总值的计数 例如:id-> 总共 15 个 -> 4

请建议如何使用 filter 和 reduce 一起按 id 对数组进行排序并计算每个 id 的总数。

【问题讨论】:

    标签: jquery filter


    【解决方案1】:

    使用您将 id 值设置为键并将总和设置为值的对象

    var newly = [
                    {"id":"15","cm_id":"31","name":"nims","total":1},
                    {"id":"15","cm_id":"61","name":"bims forum","total":3},
                    {"id":"80","cm_id":"198","name":"rims for topic","total":2}
                    ];
                    
     var idTotals = {};
     
     newly.forEach(({id, total}) => idTotals[id] = (idTotals[id] || 0) + total)
     
     console.log(idTotals)

    【讨论】:

      【解决方案2】:

      你可以试试这个方法

      var totalCount = {};
      var newly = [
                      {"id":"15","cm_id":"31","name":"nims","total":1},
                      {"id":"15","cm_id":"61","name":"bims forum","total":3},
                      {"id":"80","cm_id":"198","name":"rims for topic","total":2}
                  ];
      
      for(const {id,total} of newly) {
          totalCount[id] = (id in totalCount) ? totalCount[id]+=total : total
      }  
      
      for(const id in totalCount){
          console.log(`id-> ${id} total -> ${totalCount[id]}`)
      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-23
        • 1970-01-01
        • 2019-12-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多