【问题标题】:Sum all properties of objects in array对数组中对象的所有属性求和
【发布时间】:2016-12-03 07:33:26
【问题描述】:

我有以下数据集:

const input = [
  { x: 1, y: 3 },
  { y: 2, f: 7 },
  { x: 2, z: 4 }
];

我需要对所有数组元素求和以获得以下结果:

const output = { f: 7, x: 3, y: 5, z: 4 };

我不知道参数名称,所以我们不应该把它放在任何地方。

将输入数组中的所有对象合并(汇总属性)为一个的最短方法是什么?

有可能使用 ES6 特性和 lodash。

【问题讨论】:

  • 来自具有很高声誉的用户的低质量问题。失望-_-
  • @naomik 不要评判 - 每个人都有最糟糕的一天。

标签: javascript ecmascript-6 lodash


【解决方案1】:

我猜这是最短的解决方案:

const input = [
  { x: 1, y: 3 },
  { y: 2, f: 7 },
  { x: 2, z: 4 }
];

let result = _.mergeWith({}, ...input, _.add);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>

文档:

如果input 的第一个元素被替换没问题,你可以省略第一个参数:

 _.mergeWith(...input, _.add)

【讨论】:

    【解决方案2】:

    Array#forEach 方法与Object.keys 方法一起使用。

    const input = [{
      x: 1,
      y: 3
    }, {
      y: 2,
      f: 7
    }, {
      x: 2,
      z: 4
    }];
    
    // object for result
    var res = {};
    
    // iterate over the input array
    input.forEach(function(obj) {
      // get key from object and iterate
      Object.keys(obj).forEach(function(k) {
        // define or increment object property value
        res[k] = (res[k] || 0) + obj[k];
      })
    })
    
    console.log(res);

    ES6 arrow function

    const input = [{
      x: 1,
      y: 3
    }, {
      y: 2,
      f: 7
    }, {
      x: 2,
      z: 4
    }];
    
    var res = {};
    
    input.forEach(obj => Object.keys(obj).forEach(k => res[k] = (res[k] || 0) + obj[k]))
    
    console.log(res);

    【讨论】:

      【解决方案3】:

      您可以迭代键并求和。

      var input = [{ x: 1, y: 3 }, { y: 2, f: 7 }, { x: 2, z: 4 }],
          sum = input.reduce((r, a) => (Object.keys(a).forEach(k => r[k] = (r[k] || 0) + a[k]), r), {});
      console.log(sum);

      【讨论】:

        【解决方案4】:

        使用_.mergeWith

        _.reduce(input, function(result, item) {
            return _.mergeWith(result, item, function(resVal, itemVal) {
                return itemVal + (resVal || 0);
            });
        }, {});
        

        【讨论】:

          【解决方案5】:

          const input = [
            { x: 1, y: 3 },
            { y: 2, f: 7 },
            { x: 2, z: 4 }
          ];
          
          function sumProperties(input) {
            return input.reduce((acc, obj) => {
              Object.keys(obj).forEach((key) => {
                if (!acc[key]) {
                  acc[key] = 0
                }
                acc[key] += obj[key]
              })
              return acc
            }, {})
          }
          
          console.log(
            sumProperties(input) 
          )

          【讨论】:

            【解决方案6】:

            forEachObject.keys 结合可以工作

            const input = [
              { x: 1, y: 3 },
              { y: 2, f: 7 },
              { x: 2, z: 4 }
            ];
            
            const output = { f: 7, x: 3, y: 5, z: 4 };
            
            output = {}
            input.forEach(function(obj){
                Object.keys(obj).forEach(function(key){
                    output.key = output.key ? output.key + key || key
                })
            })
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2013-10-14
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2017-08-04
              相关资源
              最近更新 更多