我有两个对象数组,我想对具有相同键(在本例中为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]"}
结果。
发布于 2019-06-10 01:23:52
通过扩展到Array.concat()
来组合这两个数组。将项目减少到地图中,同时将当前项目与地图中已存在的项目合并。通过展开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)
发布于 2019-06-10 01:17:23
我建议在这里使用Array.reduce
。在result函数的主体中,如果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));
https://stackoverflow.com/questions/56516631
复制相似问题