js两个id相同的数组怎么合并
2021-06-09 15:58:23 来源:admin 点击:663
var arr2 = [{ id: 1, name: '小明' }, { id: 2, name: '卢本伟' }, { id: 3, name: 'PDD' }, { id: 4, name: '大司马' }]
var arr1 = [{ id: 1, car: '奔驰' }, { id: 2, car: '宝马' }, { id: 3, car: '劳斯' }, { id: 4, car: '大众' }]
// 方法如下
const combined = arr2.reduce((acc, cur) => {
const target = acc.find(e => e.id === cur.id);
if (target) {
Object.assign(target, cur);
} else {
acc.push(cur);
}
return acc;
}, arr1);
console.log(combined)