javascript – 合并两个对象并将相同键的值相加的最佳方法?

我有两个与此类似的对象:

let data = [[
  {
    10: {key1: 1, key2: 2, key3: 3},
    11: {key1: 1, key2: 2, key3: 3},
    12: {key1: 1, key2: 2, key3: 3},
    },
  {},
  {}
],
[
  {
    10: {key1: 1, key2: 2, key3: 3},
    11: {key1: 1, key2: 2, key3: 3},
    12: {key1: 1, key2: 2, key3: 3},
    },
  {},
  {}
]]

我想创建一个新对象并对每个键的每个值求和.像这样:

let newData = [
      {
        10: {key1: 2, key2: 4, key3: 6},
        11: {key1: 2, key2: 4, key3: 6},
        12: {key1: 2, key2: 4, key3: 6},
        },
      {},
      {}
    ]

每个对象都有三个对象.在这三个对象中,有45个键,每个键都有一个具有三个键/值的对象.

我找不到任何好的解决方案来总结每一个价值.

我目前的解决方案是我首先循环数据:

let count = 0;
let count2 = 0;
for(let ob of data){
     for(let child in ob[0]){
          keyOne = ob[0][child].keyOne;
          keyTwo = ob[0][child].keyTwo;
          keyThree = ob[0][child].keyThree;
          keyFour = ob[0][child].keyFour;
          if(count < 45) {
               newData[0][count].keyOne += keyOne;
               newData[0][count].keyTwo += gkeyTwop;
               newData[0][count].keyThree += keyThree;
               newData[0][count].keyFour += keyFour;
          } else {
               newData[0][count2].keyOne += keyOne;
               newData[0][count2].keyTwo += keyTwo;
               newData[0][count2].keyThree += keyThree;
               newData[0][count2].keyFour += keyFour;
               count2++;

          }
          count++;
     }

在最坏的情况下,数据有三个对象,每个对象有45个密钥.然后我必须这样做三次.这看起来真的很糟糕.肯定有更好的办法.提示?

最佳答案 这是使用reduce()和少量forEach()循环的解决方案,因为您还需要循环嵌套对象.

var data = [[{"10":{"key1":1,"key2":2,"key3":3},"11":{"key1":1,"key2":2,"key3":3},"12":{"key1":1,"key2":2,"key3":3}},{},{}],[{"10":{"key1":1,"key2":2,"key3":3},"11":{"key1":1,"key2":2,"key3":3},"12":{"key1":1,"key2":2,"key3":3}},{},{}]]

var result = data.reduce(function(r, e, i) {
  if (i == 0) r = r.concat(e)
  else  {
  e.forEach(function(a, j) {
       Object.keys(a).forEach(function(key) {
          if (!r[j][key]) r[j][key] = a[key]
          else {
            Object.keys(a[key]).forEach(function(k) {
              r[j][key][k] += a[key][k]
            })
          }
      })
    })
  }
  return r;
}, [])

console.log(result)
点赞