有以下对象数组:
const list =[
{ name: "张三", age: 18, address: "北京" },
{ name: "李四", age: 20, address: "天津" },
{ name: "王五", age: 22, address: "河北" },
{ name: "张三", age: 18, address: "北京" },
{ name: "李四", age: 20, address: "天津" },
]
其中张三和李四为重复对象;
使用Set数据结构去除重复对象:
const strings = list.map((item) => JSON.stringify(item));
const removeDupList = [...new Set(strings)]; //也可以使用Array.from(new Set(strings))
const result = removeDupList.map((item) => JSON.parse(item));
// result
// [
// { name: "张三", age: 18, address: "北京" },
// { name: "李四", age: 20, address: "天津" },
// { name: "王五", age: 22, address: "河北" },
// ]
解释一下上面为什么要将new Set(strings)进行转型。因为Set数据结构并非真正的数组,它类似于数组,并且成员值都是唯一的,没有重复,所以可以用来做去重操作。但是因为它是一个类似数组结构,所以需要转型为真正的数组去使用。