我有一个包含对象数组的对象。

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"}

当前回答

let data = [
  {
    'name': 'Amir',
    'surname': 'Rahnama'
  }, 
  {
    'name': 'Amir',
    'surname': 'Stevens'
  }
];
let non_duplicated_data = _.uniqBy(data, 'name');

其他回答

您可以使用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

Dang,孩子们,让我们把这件事搞砸,为什么不呢?

让uniqIds={},source=〔{id:‘a’},{id:'b‘},{id:'c‘}、{id:s'b‘},{id:‘a‘};let filtered=source.filter(obj=>!uniqIds[obj.id]&&(uniqIds[obj.id]=true));console.log(已过滤);//预期:[{id:'a'},{id:'b'};

如果您可以使用诸如下划线或lodash之类的Javascript库,我建议查看它们库中的_.uniq函数。来自lodash:

_.uniq(array, [isSorted=false], [callback=_.identity], [thisArg])

基本上,您传入数组,这里是一个对象文本,然后传入要在原始数据数组中删除重复项的属性,如下所示:

var data = [{'name': 'Amir', 'surname': 'Rahnama'}, {'name': 'Amir', 'surname': 'Stevens'}];
var non_duplidated_data = _.uniq(data, 'name'); 

更新:Lodash现在也引入了.uniqBy。

要从对象数组中删除所有重复项,最简单的方法是使用过滤器:

var uniq={};var arr=[{“id”:“1”},{“id”:“2”};var arrFiltered=arr.filter(obj=>!uniq[obj.id]&&(uniq[obj.id]=true));console.log('arrFiltered',arrFiltered);

这里是ES6的解决方案,您只想保留最后一项。该解决方案功能强大,符合Airbnb风格。

const things = {
  thing: [
    { place: 'here', name: 'stuff' },
    { place: 'there', name: 'morestuff1' },
    { place: 'there', name: 'morestuff2' }, 
  ],
};

const removeDuplicates = (array, key) => {
  return array.reduce((arr, item) => {
    const removed = arr.filter(i => i[key] !== item[key]);
    return [...removed, item];
  }, []);
};

console.log(removeDuplicates(things.thing, 'place'));
// > [{ place: 'here', name: 'stuff' }, { place: 'there', name: 'morestuff2' }]