我有一个包含对象数组的对象。
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);
您可以使用Set和Filter方法来实现这一点,
变量arrObj=[{a: 1中,b: 2个}, {a: 1中,b: 1个}, {a: 1中,b: 2个}];var duplicateRemove=新集合();var distinctArObj=arrObj.filter((obj)=>{if(duplicateRemove.has(JSON.stringify(obj)))返回false;duplicateRemove.add(JSON.stringify(obj));返回true;});console.log(distinctArObj);
Set是一个唯一的基元类型集合,因此不会直接作用于对象,但是JSON.stringify会将其转换为基元类型,即String,因此我们可以过滤。
如果您希望仅基于某个特定的键(例如key)删除重复项,可以将JSON.stringify(obj)替换为obj.key
让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)最后,传播。。。运算符为新数组提供上述步骤中的值。