两个数组对象合并,相同的对象覆盖成最新的,不相同的合并并去重
let arr1 = [
{ id: 1, name: "独行月球", price: 30 },
{ id: 2, name: "满江红", price: 35 },
];
let arr1Set = new Set(arr1.map((item) => item.id));
let arr2 = [
{ id: 1, name: "这个杀手不太冷", price: 30 },
{ id: 2, name: "满江红", price: 60 },
];
let arr2Map = new Map(arr2.map((item) => [item.id, item]));
let newArr = arr1.map((item) => {
if (arr2Map.has(item.id)) {
return { ...item, ...arr2Map.get(item.id) };
}
return { ...item };
}).concat(...arr2.filetr((item) => !arr1Set.has(item.id)));
let uniqueArr = Array.from(new Set(newArr.map((item) => item.id))).map((id) => {
return newArr.find((item) => item.id === id);
});
console.log(uniqueArr);