我有一个包含对象数组的对象。
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 things = [{place:"here",name:"stuff"}, ...];
const distinctThings = distinct(things, thing => thing.place);
不同的函数可以使用上面许多好答案中给出的任何实现。最简单的方法是使用findIndex:
const distinct = (items, predicate) => items.filter((uniqueItem, index) =>
items.findIndex(item =>
predicate(item) === predicate(uniqueItem)) === index);
让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)最后,传播。。。运算符为新数组提供上述步骤中的值。
这是我的解决方案,将实际数组添加到键值对象中,其中键将是唯一标识,值可以是对象或整个对象的任何属性。
说明:具有重复项的主数组将转换为键/值对象如果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}));
})
);
}