您可以使用reduce
方法和Set
数据结构来解决这个问题。下面是一个示例代码:
// 原始对象数组
const originalArray = [
{ id: 1, name: "John" },
{ id: 2, name: "Jane" },
{ id: 3, name: "John" },
{ id: 4, name: "Jane" },
];
// 根据name属性创建新的对象数组,不包含重复项
const newArray = originalArray.reduce((acc, cur) => {
// 使用Set数据结构来判断是否已经存在相同的name属性
const isNameExists = acc.some(obj => obj.name === cur.name);
// 如果name属性不存在重复项,则将当前对象添加到新的数组中
if (!isNameExists) {
acc.push(cur);
}
return acc;
}, []);
console.log(newArray);
输出结果为:
[
{ id: 1, name: "John" },
{ id: 2, name: "Jane" },
]
在上面的示例代码中,我们使用reduce
方法来遍历原始对象数组originalArray
。对于每个元素,我们使用some
方法和箭头函数来检查新数组acc
中是否已经存在相同的name属性。如果不存在重复项,则将当前对象cur
添加到新数组中。最终返回新的对象数组。