JavaScript 对象数组去重:使用 Set 和 Array.from() 方法
可以使用 Set 数据结构和 Array.from() 方法来实现对象数组的去重:
const arr = [
{ name: 'Alice', age: 18 },
{ name: 'Bob', age: 20 },
{ name: 'Alice', age: 18 }
];
const uniqueArr = Array.from(new Set(arr.map(JSON.stringify))).map(JSON.parse);
console.log(uniqueArr);
// output: [{ name: 'Alice', age: 18 }, { name: 'Bob', age: 20 }]
首先,使用 map() 方法将对象数组转换成字符串数组,每个对象使用 JSON.stringify() 方法转换成字符串。然后,创建一个 Set 数据结构并将字符串数组作为参数传入,Set 数据结构会自动去重。接着,使用 Array.from() 方法将 Set 转换成数组,并使用 map() 方法将每个字符串转换成对象,使用 JSON.parse() 方法进行转换。最后,得到去重后的对象数组 uniqueArr。
原文地址: https://www.cveoy.top/t/topic/m891 著作权归作者所有。请勿转载和采集!