JavaScript 数组去重:保留相同属性值最后一个对象
可以使用 reduce() 方法和 Object.assign() 方法进行去重,以最后一个为准:
let arr = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'John' },
{ id: 4, name: 'Jack' },
{ id: 1, name: 'Johnny' }
];
let uniqueArr = arr.reduce((acc, current) => {
let existing = acc.find(item => item.id === current.id);
if (existing) {
Object.assign(existing, current);
} else {
acc.push(current);
}
return acc;
}, []);
console.log(uniqueArr); // [{id: 2, name: 'Jane'}, {id: 3, name: 'John'}, {id: 4, name: 'Jack'}, {id: 1, name: 'Johnny'}]
在这个例子中,reduce() 方法遍历数组 arr,并且通过 find() 方法查找是否已经存在具有相同 id 属性的对象。如果找到了,则使用 Object.assign() 方法将新的对象属性值覆盖旧的对象属性值,否则将新的对象推到结果数组中。最终返回一个去重后的结果数组 uniqueArr。
原文地址: https://www.cveoy.top/t/topic/mNCI 著作权归作者所有。请勿转载和采集!