Mav*_*vys 3 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 } ]
Run Code Online (Sandbox Code Playgroud)
和
var dataTwo = [ { id:"1", total: 5, win: 2 }, { id:"2", total: 2, win: 3 }, { id:"5", total: 5, win: 4 } ]
Run Code Online (Sandbox Code Playgroud)
预期结果:
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 } ]
Run Code Online (Sandbox Code Playgroud)
我尝试使用将对象数组中的所有数据求和到新的对象数组中的解决方案 ,但显然数据类型有点不同
所以,我尝试使用Javascript 中的方法 - 具有相同属性的两个对象的总和
function sumObjectsByKey(...objs) {
for (var prop in n) {
if (acc.hasOwnProperty(prop)) acc[prop] += n[prop];
else acc[prop] = n[prop];
}
return acc;
}
Run Code Online (Sandbox Code Playgroud)
和
var combinedData = sumObjectsByKey(dataOne, dataTwo);
Run Code Online (Sandbox Code Playgroud)
但显然,该方法不适用于对象数组。我明白了
{0: "0[object Object][object Object]", 1: "0[object Object][object Object]", 2: "0[object Object][object Object]"}
Run Code Online (Sandbox Code Playgroud)
因此。
使用剩余参数和 组合两者Array.flat()。将项目缩减为 Map,同时将当前项目与 Map 中已存在的项目组合起来。使用以下命令将迭代器转换Map.values()为数组Array.from():
const sumObjectsByKey = (sumFn, ...arrs) => Array.from(
arrs.flat() // 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) ? sumFn(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()
)
// 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 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(sumItem, dataOne, dataTwo)
console.log(result)Run Code Online (Sandbox Code Playgroud)