function uniqueObjectsByProperty(arr, property) {
return arr.reduce((acc, current) => {
// 检查是否已存在具有相同属性值的对象
const existingItem = acc.find(item => item[property] === current[property]);
// 如果不存在,则将当前对象添加到结果数组中
if (!existingItem) {
acc.push(current);
}
return acc;
}, []);
}
// 假设数组名为arr,每个元素是包含qwe属性的对象
const arr = [
{ qwe: 'A', otherProp: 'value1' },
{ qwe: 'B', otherProp: 'value2' },
{ qwe: 'A', otherProp: 'value3' },
{ qwe: 'C', otherProp: 'value4' },
{ qwe: 'B', otherProp: 'value5' },
];
// 传入数组和属性名进行去重
const uniqueArr = uniqueObjectsByProperty(arr, 'qwe');
console.log(uniqueArr);
这里演示的是根据数组中的qwe属性去重