我有一个包含对象数组的对象。
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"}
带有Map的一行程序(高性能,不保留顺序)
在数组arr中查找唯一id。
const arrUniq = [...new Map(arr.map(v => [v.id, v])).values()]
如果订单很重要,请检查带过滤器的解决方案:带过滤器的方案
由数组arr中的多个财产(位置和名称)唯一
const arrUniq = [...new Map(arr.map(v => [JSON.stringify([v.place,v.name]), v])).values()]
由数组arr中的所有财产唯一
const arrUniq = [...new Map(arr.map(v => [JSON.stringify(v), v])).values()]
保留数组arr中的第一次出现
const arrUniq = [...new Map(arr.slice().reverse().map(v => [v.id, v])).values()].reverse()
您也可以使用地图:
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"
}
]