来自两个对象数组的数据总和

时间:2019-06-09 17:00:46

标签: javascript arrays object

我有两个对象数组,我想对具有相同键(在本例中为id)的对象求和,如果没有匹配键,则只需创建一个新键即可。如果我没有清楚地解释它,那我是JavaScript / Array / Object的新手...

var dataOne = [ { id:"1", total: 10, win: 5 }, { id:"2", total: 5, win: 1 }, { id:"3", total: 5, win: 2 } ]

var dataTwo = [ { id:"1", total: 5, win: 2 }, { id:"2", total: 2, win: 3 }, { id:"5", total: 5, win: 4 } ]

预期结果:

var combinedData = [ { id:"1", total: 15, win: 7 }, { id:"2", total: 7, win: 4 }, { id:"3", total: 5, win: 2 }, { id:"5", total: 5, win: 4 } ]

我尝试使用Sum all data in array of objects into new array of objects中的解决方案 但是,显然数据的类型有所不同

因此,我尝试从Javascript - Sum of two object with same properties

使用此方法
 function sumObjectsByKey(...objs) {
      for (var prop in n) {
        if (acc.hasOwnProperty(prop)) acc[prop] += n[prop];
        else acc[prop] = n[prop];
      }
      return acc;
    }

var combinedData = sumObjectsByKey(dataOne, dataTwo);

但是显然,该方法不适用于对象数组。 我得到

{0: "0[object Object][object Object]", 1: "0[object Object][object Object]", 2: "0[object Object][object Object]"}

因此。

2 个答案:

答案 0 :(得分:1)

我会在这里建议Array.reduce。在归约函数的主体中,如果id不在结果累加器中,则将其添加,然后递增对象中每个属性的所有值。

var dataOne = [ { id:"1", total: 10, win: 5 }, { id:"2", total: 5, win: 1 }, { id:"3", total: 5, win: 2 } ]
var dataTwo = [ { id:"1", total: 5, win: 2 }, { id:"2", total: 2, win: 3 }, { id:"5", total: 5, win: 4 } ]

var sumObjectsByKey = (...objs) => 
  Object.values(objs.reduce((a, e) => {
    a[e.id] = a[e.id] || {id: e.id};

    for (const k in e) {
      if (k !== "id") {
        a[e.id][k] = a[e.id][k] ? a[e.id][k] + e[k] : e[k];
      }
    }

    return a;
  }, {}))
;

console.log(sumObjectsByKey(...dataOne, ...dataTwo));

答案 1 :(得分:1)

将两个数组组合成Array.concat()。在将当前项目与Map中已经存在的项目合并的同时,将项目简化为Map。通过传播Map.values()迭代器将其转换回数组:

// utility function to sum to object values (without the id)
const sumItem = ({ id, ...a }, b) => ({
  id,
  ...Object.keys(a)
    .reduce((r, k) => ({ ...r, [k]: a[k] + b[k] }), {})
});

const sumObjectsByKey = (...arrs) => [...
  [].concat(...arrs) // combine the arrays
  .reduce((m, o) => // retuce the combined arrays to a Map
    m.set(o.id, // if add the item to the Map
      m.has(o.id) ? sumItem(m.get(o.id), o) : { ...o } // if the item exists in Map, sum the current item with the one in the Map. If not, add a clone of the current item to the Map
    )
  , new Map).values()]

const dataOne = [ { id:"1", total: 10, win: 5 }, { id:"2", total: 5, win: 1 }, { id:"3", total: 5, win: 2 } ]
const dataTwo = [ { id:"1", total: 5, win: 2 }, { id:"2", total: 2, win: 3 }, { id:"5", total: 5, win: 4 } ]

const result = sumObjectsByKey(dataOne, dataTwo)
  
console.log(result)