1 回答
TA贡献1835条经验 获得超7个赞
您可以减少第二个数组并将所需的键作为查找的通用部分。
var array1 = [{ hour: "565", age: "21", id: "1", naban: "sdfsd" }, { hour: "515", age: "25", id: "2", naban: "sf" }],
array2 = [{ hour: "56454", age: "21", id: "1", too: "898" }, { hour: "8979", age: "25", id: "2", too: "234234" }, { hour: "65465", age: "27", id: "6", too: "123" }],
data = [array1, array2],
keys = ['id', 'id'],
merged = data[1].reduce((r, o) => {
var temp = r.find(q => o[keys[0]] === q[keys[1]]);
if (temp) {
Object
.entries(o)
.forEach(([k, v]) => {
if (keys.includes(k)) return;
temp[k in temp ? k + 2 : k] = v;
});
} else {
r.push({ ...o });
}
return r;
}, data[0]);
console.log(merged);
.as-console-wrapper { max-height: 100% !important; top: 0; }
添加回答
举报