我有一个包含对象数组的对象。
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 uniqueElements = (arr, fn) => arr.reduce((acc, v) => {
if (!acc.some(x => fn(v, x))) { acc.push(v); }
return acc;
}, []);
const stuff = [
{place:"here",name:"stuff"},
{place:"there",name:"morestuff"},
{place:"there",name:"morestuff"},
];
const unique = uniqueElements(stuff, (a,b) => a.place === b.place && a.name === b.name );
//console.log( unique );
[{
"place": "here",
"name": "stuff"
},
{
"place": "there",
"name": "morestuff"
}]
来源
JSFiddle公司
这将在不传递任何键的情况下删除重复对象。
uniqueArray=a=>[…new Set(.map(o=>JSON.stringify(o))].map(s=>JSON.parse(s));var objects=[{'x':1,'y':2},{'x':2,'y':1},{'x':1,'y':2}];var unique=uniqueArray(对象);console.log(“原始对象”,对象);console.log(“唯一”,唯一);
uniqueArray = a => [...new Set(a.map(o => JSON.stringify(o)))].map(s => JSON.parse(s));
var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
var unique = uniqueArray(objects);
console.log(objects);
console.log(unique);