【问题标题】:Add values of matching keys in array of objects在对象数组中添加匹配键的值
【发布时间】:2016-03-01 10:52:59
【问题描述】:

我有一个数组,其中包含许多具有匹配键的对象:

[{a: 2, b: 5, c: 6}, {a:3, b: 4, d:1},{a: 1, d: 2}]

我想循环遍历数组,如果键匹配,我想添加每个的结果并返回一个对象和每个键的总和。

{a: 6, b: 9, c: 6, d: 3}

我目前拥有的代码是

function combine() {
   var answer = [];
  for(var i in arguments){
    answer.push(arguments[i])
  }

 answer.reduce(function(o) {
    for (var p in o)
        answer[p] = (p in answer ? answer[p] : 0) + o[p];
        return answer;
    }, {});
}

如果我要使用下划线库,我可以找到答案here,但是我希望不使用库来做到这一点。我想我很难理解 reduce 方法的工作原理 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

任何有关如何解决此问题的帮助将不胜感激。另外,我觉得这个答案应该在 SO 上的某个地方,而不必使用库。

提前致谢。

【问题讨论】:

  • 还要提到你得到的输出。

标签: javascript arrays object


【解决方案1】:

使用 Array.reduce() 和 Array.map()

var tab = [{a: 2, b: 5, c: 6}, {a:3, b: 4, d:1},{a: 1, d: 2}];

function sum(tab) {
  return tab.reduce((a, b) => {
    Object.keys(b).map(c => a[c] = (a[c] || 0) + b[c]);
    return a;
  });
}

console.log(sum(tab));

【讨论】:

    【解决方案2】:

    遍历每个对象并添加它。

        var a = [{a: 2, b: 5, c: 6}, {a:3, b: 4, d:1},{a: 1, d: 2}];
        var ans = {};
    
        for(var i = 0; i < a.length; ++i){
          for(var obj in a[i]){
           ans[obj] = ans[obj] ? ans[obj] + a[i][obj] : a[i][obj];
          }
        }
    document.write(JSON.stringify(ans));

    ans[obj] = ans[obj] ? ans[obj] + a[i][obj] : a[i][obj];
    
    This line is the same as    
    // check if the object already exists(or not falsy) in answer, if Yes add that value to the new value
    if(ans[obj])
    {
      ans[obj] = ans[obj] + a[i][obj];
    }
    // else create a new object in the answer and set it to the value from the array
    else
    {
      ans[obj] = a[i][obj];
    }
    

    【讨论】:

    • 谢谢,这行得通。但是,我对ans[obj] = ans[obj] ? ans[obj] + a[i][obj] : a[i][obj]; 这一行有点困惑。您介意在答案中解释一下吗?
    【解决方案3】:

    reduce() 中的回调函数需要两个参数:

    1. 返回前一个值的结果(如果是第一个值,则返回初始值)
    2. 循环中的当前值

    您还应该将一个空对象作为第二个参数传递给 reduce。这是你要填写的。

    var input = [
      {a: 2, b: 5, c: 6},
      {a: 3, b: 4, d: 1},
      {a: 1, d: 2}
    ];
    
    var answer = input.reduce(function(prev, curr) {
        for (var p in curr) {
            prev[p] = (prev[p] || 0) + curr[p];
        }
    
        return prev; // this will be passed as prev in the next iteration or returned as the result.
    }, {}); // The {} is the initial value passed as prev
    
    console.log(answer);

    【讨论】:

      【解决方案4】:

      另一个使用reduce的解决方案:

      var result = [{a: 2, b: 5, c: 6}, {a:3, b: 4, d:1},{a: 1, d: 2}].reduce(function(prev, current) {
          Object.keys(current).forEach(function(key) {
              prev[key] = (prev[key] || 0) + current[key]; 
          });
          return prev;
      }, {});
      
      document.write('<pre>' + JSON.stringify(result, 0, 2) + '</pre>');

      【讨论】:

        【解决方案5】:

        试试这个

        resobj = {};
        [{a: 2,b: 5,c: 6}, {a: 3,b: 4,d: 1}, {a: 1,d: 2}].forEach(function(v) {
        
          var keys = Object.keys(v);
          for (i = 0; i < keys.length; i++) {
            if (typeof resobj[keys[i]] == 'undefined') {
              resobj[keys[i]] = Number(v[keys[i]]);
            } else {
              resobj[keys[i]] += v[keys[i]];
            }
          }
        
        })
        
        document.write(JSON.stringify(resobj))

        【讨论】:

          【解决方案6】:

          只需使用Array#forEach() 和一个对象作为结果。

          var data = [{ a: 2, b: 5, c: 6 }, { a: 3, b: 4, d: 1 }, { a: 1, d: 2 }],
              obj = {};
          
          data.forEach(function (o) {
              Object.keys(o).forEach(function (k) {
                  obj[k] = (obj[k] || 0) + o[k];
              });
          })
          document.write('<pre>' + JSON.stringify(obj, 0, 4) + '</pre>');

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-06-18
            • 2019-08-30
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-05-17
            • 2021-07-01
            • 1970-01-01
            相关资源
            最近更新 更多