我有一个包含对象数组的对象。
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"}
您还可以创建一个通用函数,该函数将根据传递给该函数的对象键过滤数组
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
可以使用for循环和条件使其唯一
const data = [
{ id: 1 },
{ id: 2 },
{ id: 3 },
{ id: 4 },
{ id: 5 },
{ id: 6 },
{ id: 6 },
{ id: 6 },
{ id: 7 },
{ id: 8 },
{ id: 8 },
{ id: 8 },
{ id: 8 }
];
const filtered= []
for(let i=0; i<data.length; i++ ){
let isHasNotEqual = true
for(let j=0; j<filtered.length; j++ ){
if (filtered[j].id===data[i].id){
isHasNotEqual=false
}
}
if (isHasNotEqual){
filtered.push(data[i])
}
}
console.log(filtered);
/*
output
[ { id: 1 },
{ id: 2 },
{ id: 3 },
{ id: 4 },
{ id: 5 },
{ id: 6 },
{ id: 7 },
{ id: 8 } ]
*/
让myData=[{place:“here”,name:“stuff”},{地点:“there”,名称:“morestuff”},{地点:“there”,名称:“morestuff”}];let q=[…new Map(myData.Map(obj=>[JSON.stringify(obj),obj]).values()];控制台日志(q)
一个使用ES6和new Map()的命令行。
// assign things.thing to myData
let myData = things.thing;
[...new Map(myData.map(obj => [JSON.stringify(obj), obj])).values()];
详细信息:-
对数据列表执行.map()并将每个单独的对象转换为[key,value]对数组(长度=2),第一个元素(key)将是对象的字符串化版本,第二个元素(value)将是一个对象本身。将上述创建的数组列表添加到新的Map()中会将键作为字符串化对象,任何相同的键添加都会导致覆盖现有的键。使用.values()将为MapIterator提供Map中的所有值(在本例中为obj)最后,传播。。。运算符为新数组提供上述步骤中的值。