js 根据数组对象的属性去重
可以使用Set数据结构来实现数组对象的属性去重。首先,将数组对象的属性值提取出来,然后将其放入Set中,最后将Set转换为数组即可。
const arr = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 1, name: 'John' },
{ id: 3, name: 'David' }
];
const uniqueArr = Array.from(new Set(arr.map(obj => obj.id)));
console.log(uniqueArr); // [1, 2, 3]
以上代码中,arr.map(obj => obj.id)将数组对象的属性id提取出来,然后new Set将其放入Set中,这样重复的id会被自动去重。最后,使用Array.from将Set转换为数组。
原文地址: http://www.cveoy.top/t/topic/iFjU 著作权归作者所有。请勿转载和采集!