JS/TS 对数组中的对象按对象的值进行去重
举个例子:对以下数组按 lastName 的值进行去重
let listData = [
{ firstName: "Rick", lastName: "Sanchez", size: 18 },
{ firstName: "Morty", lastName: "Smith", size: 6 },
{ firstName: "Jerry", lastName: "Smith", size: 3 },
{ firstName: "Beth", lastName: "Smith", size: 0 },
{ firstName: "Summer", lastName: "Smith", size: 0 },
{ firstName: "Rick", lastName: "Sanchez", size: 18 },
{ firstName: "Morty", lastName: "Smith", size: 6 },
];
去重前:
去重后:
一、普通写法
let obj = {};
listData = listData.reduce((item, next) => {
if (!obj[next.lastName]) {
item.push(next);
obj[next.lastName] = true;
}
return item;
}, []);
二、TS 写法
const obj: {[key: string]: boolean;} = {};
listData = listData.reduce<ListDataItem[]>((item, next) => {
if (!obj[next.lastName]) {
item.push(next);
obj[next.lastName] = true;
}
return item;
},[]);
赞 (0)