我有一个包含对象数组的对象。
obj = {};
obj.arr = new Array();
obj.arr.push({place:"here",name:"stuff"});
obj.arr.push({place:"there",name:"morestuff"});
obj.arr.push({place:"there",name:"morestuff"});
我想知道从数组中删除重复对象的最佳方法是什么。例如,obj.arr将变成。。。
{place:"here",name:"stuff"},
{place:"there",name:"morestuff"}
如果数组包含对象,则可以使用此方法删除重复的
const persons= [
{ id: 1, name: 'John',phone:'23' },
{ id: 2, name: 'Jane',phone:'23'},
{ id: 1, name: 'Johnny',phone:'56' },
{ id: 4, name: 'Alice',phone:'67' },
];
const unique = [...new Map(persons.map((m) => [m.id, m])).values()];
如果删除基于电话的重复项,只需将m.id替换为m.phone
const unique = [...new Map(persons.map((m) => [m.phone, m])).values()];
这是我的解决方案,将实际数组添加到键值对象中,其中键将是唯一标识,值可以是对象或整个对象的任何属性。
说明:具有重复项的主数组将转换为键/值对象如果Id已存在于唯一对象中,则该值将被覆盖。最后,只需将唯一对象转换为数组。
getUniqueItems(array) {
const unique = {};
// here we are assigning item.name but it could be a complete object.
array.map(item => unique[item.Id] = item.name);
// here you can transform your array item like {text: unique[key], value: key} but actually you can do what ever you want
return Object.keys(unique).map(key => ({text: unique[key], value: key}));
})
);
}