【问题标题】:Adding values from objects in an array从数组中的对象添加值
【发布时间】:2017-02-23 17:10:24
【问题描述】:

我有一个对象数组:

var array = [{
    id: "cards",
    amount: 5
}, {
    id: "shirts",
    amount: 3
}, {
    id: "cards",
    amount: 2
}, {
    id: "shirts",
    amount: 3
}]

我需要做的是遍历这个数组并找到所有 id 类型的总数。 所以在这个例子中,我会找到卡片和衬衫的总数。

我不确定如何处理对象。我尝试使用Object.values(array) 剥离对象,但有没有办法对对象进行处理?

感谢您的帮助。

【问题讨论】:

    标签: javascript arrays javascript-objects


    【解决方案1】:

    这应该做你想做的:

    var array = [
      { id: "cards", amount: 5 }, 
      { id: "shirts", amount: 3 },
      { id: "cards", amount: 2 }, 
      { id: "shirts", amount: 3 }
    ];
    
    var result = array.reduce(function(entities, item) {
           entities[item.id] = (entities[item.id] || 0) + item.amount;
           return entities;
    }, {})
    
    
    console.log(result);

    【讨论】:

      【解决方案2】:

      您将循环您的数组,检查目标对象的id 属性,然后使用存储在amount 属性中的值枚举外部范围变量。

      var totalShirts = 0;
      var totalCards = 0;
      for(var i = 0, len = array.length; i < len; i++){
          var entry = array[i];
          if(entry.id === "cards"){
              totalCards += entry.amount;
          }
          else if(entry.id === "shirts"){
              totalShirts += entry.amount;
          }
      }
      console.log("Total Cards: " + totalCards);
      console.log("Total Shirts: " + totalShirts);
      

      【讨论】:

        【解决方案3】:

        这是一个获取每个项目总数的示例

        var array = [{id:"cards", amount: 5}, {id:"shirts", amount: 3}, {id:"cards", amount: 2}, {id:"shirts", amount: 3}];
        
        var result = array.reduce(function(accumulator, current) {
          if (!(current.id in accumulator)) {
            accumulator[current.id] = current.amount;
          } else {
            accumulator[current.id] += current.amount;
          }
          
          return accumulator;
        }, {});
        
        console.log(result);

        【讨论】:

          【解决方案4】:

          一个简单的forEach 就可以解决问题:

          var counts = {}
          array.forEach(v => {
            counts[v.id] = (counts[v.id] || 0) + v.amount
          })
          console.log(counts)
          

          将打印:

          {
              cards: 7
              shirts: 6
          }
          

          【讨论】:

          • 是否需要return 声明?
          • @guest271314 - 我假设是因为返回会将新计数添加到计数对象...?
          • @HappyGreybush return 语句可以省略。 counts[v.id] = (counts[v.id] || 0) + v.amount 赋值。
          • 确实,return 不是必需的,我有一个使用 .map 的解决方案,我将其更改为 forEach 并忘记了:) 已编辑
          【解决方案5】:

          这是一个 O(n) 时间的解决方案。

          var totals = new Object();
          
          for(var i = 0;i < array.length;i ++) {
            var id = array[i].id;
            var amount = array[i].amount;
            if(totals[id] == undefined) {
              totals[id] = amount; 
            } else {
              totals[id] += amount;
            }
          }
          console.log(totals);
          

          【讨论】:

            【解决方案6】:

            你可以使用for..of循环

            var array = [{
              id: "cards",
              amount: 5
            }, {
              id: "shirts",
              amount: 3
            }, {
              id: "cards",
              amount: 2
            }, {
              id: "shirts",
              amount: 3
            }]
            
            let res = {};
            
            for (let {id,amount} of array) {
              if (!res.hasOwnProperty(id)) res[id] = 0;
              res[id] += amount;
            }
            
            console.log(res);

            【讨论】:

              【解决方案7】:

              使用 for 循环来做到这一点:

              var totalCards = 0; 
              var totalShirt = 0;
              for (var i = 0; i < arr.length; i++) {
                  if (arr[i].id === "cards") {
                      totalCards += arr[i].amount;
                  } else {
                      totalShirt += arr[i].amount;
                  }
              }
              

              【讨论】:

                【解决方案8】:

                在 for 循环中施展魔法。这个例子应该足够笼统:

                var array = [ {id:"cards", amount: 5}, {id:"shirts", amount: 3}, {id:"cards", amount: 2}, {id:"shirts", amount: 3} ];
                var output = [];
                    
                for(var i of array) {
                  if(!output[i.id]) {
                    output[i.id] = 0;
                  }
                  output[i.id] += i.amount;
                }
                    
                console.log(output);

                【讨论】:

                  【解决方案9】:

                  var array = [{id:"cards", amount: 5}, {id:"shirts", amount: 3}, {id:"cards", amount: 2}, {id:"shirts", amount: 3}];
                  
                  var arr = [];
                  array.forEach(v => arr.push(v.id));
                  var newArr = [...new Set(arr)];
                  var arr2 = [];
                  
                  newArr.forEach(function(v) {
                    var obj = {};
                    obj.id = v;
                    obj.counter = 0;
                    arr2.push(obj);
                  });
                  
                  arr2.forEach(v => array.forEach(c => c.id == v.id ? v.counter += c.amount : v));
                  console.log(arr2);

                  【讨论】:

                    【解决方案10】:

                    您可以使用Array.forEach() 遍历数组的每个元素。总对象是一个关联数组,其中索引是数组元素对象的id 字段。

                    var array = [{ id: "cards", amount: 5 },
                                 { id: "shirts", amount: 3 },
                                 { id: "cards", amount: 2},
                                 { id: "shirts", amount: 3 }];
                    var total = {};
                    array.forEach(function (el) {
                      if (total[el.id]) {
                        total[el.id] += el.amount
                      } else {
                        total[el.id] = el.amount
                      }
                    });
                    console.log(JSON.stringify(total));
                    

                    【讨论】:

                      【解决方案11】:

                      您可以使用Array#reduce 并求和。

                      var array = [{ id: "cards", amount: 5 }, { id: "shirts", amount: 3 }, { id: "cards", amount: 2 }, { id: "shirts", amount: 3 }],
                          result = array.reduce(function (r, a) {
                              r[a.id] = (r[a.id] || 0) + a.amount;
                              return r;
                          }, {});
                          
                      console.log(result);

                      【讨论】:

                      • 恐怕他想要的是每种类型的总量,而不是所有东西的总量。
                      • @Kinduser,我在想我错过了什么。
                      • @Kinduser 我很高兴 ;-)
                      【解决方案12】:

                      您可以使用此代码

                      if (!Object.keys) {
                          Object.keys = function (obj) {
                              var keys = [],
                                  k;
                              for (k in obj) {
                                  if (Object.prototype.hasOwnProperty.call(obj, k)) {
                                      keys.push(k);
                                  }
                              }
                              return keys;
                          };
                      }
                      

                      那么您也可以在旧版浏览器中执行此操作:

                      var len = Object.keys(obj).length;
                      

                      【讨论】:

                        猜你喜欢
                        • 1970-01-01
                        • 2021-07-01
                        • 2020-09-14
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 2020-03-28
                        • 2020-07-10
                        • 1970-01-01
                        相关资源
                        最近更新 更多