我有一个包含对象数组的对象。
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 dedupThings = Array.from(things.thing.reduce((m, t) => m.set(t.place, t), new Map()).values());
完整样本:
const things = new Object();
things.thing = new Array();
things.thing.push({place:"here",name:"stuff"});
things.thing.push({place:"there",name:"morestuff"});
things.thing.push({place:"there",name:"morestuff"});
const dedupThings = Array.from(things.thing.reduce((m, t) => m.set(t.place, t), new Map()).values());
console.log(JSON.stringify(dedupThings, null, 4));
结果:
[
{
"place": "here",
"name": "stuff"
},
{
"place": "there",
"name": "morestuff"
}
]
您还可以创建一个通用函数,该函数将根据传递给该函数的对象键过滤数组
function getUnique(arr, comp) {
return arr
.map(e => e[comp])
.map((e, i, final) => final.indexOf(e) === i && i) // store the keys of the unique objects
.filter(e => arr[e]).map(e => arr[e]); // eliminate the dead keys & store unique objects
}
你可以这样调用函数,
getUnique(things.thing,'name') // to filter on basis of name
getUnique(things.thing,'place') // to filter on basis of place
另一种方法是使用reduce函数,并使用一个新数组作为累加器。如果累加器数组中已经有一个同名的对象,那么不要将其添加到那里。
let list = things.thing;
list = list.reduce((accumulator, thing) => {
if (!accumulator.filter((duplicate) => thing.name === duplicate.name)[0]) {
accumulator.push(thing);
}
return accumulator;
}, []);
thing.things = list;
我添加了这个答案,因为我找不到与InternetExplorer11兼容的好的、可读的es6解决方案(我使用babel来处理箭头函数)。问题是IE11没有没有polyfill的Map.values()或Set.values)。出于同样的原因,我使用filter()[0]来获取第一个元素,而不是find()。