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

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

当前回答

继续探索ES6从对象数组中删除重复项的方法:将array.prototype.filter的thisArg参数设置为new Set提供了一个不错的选择:

常量=[{地点:“这里”,名称:“东西”},{地点:“there”,名称:“morestuff”},{地点:“there”,名称:“morestuff”}];constfiltered=things.filter(函数({place,name}){const key=“${place}${name}”;回来this.has(key)&&this.add(key);},新设置);console.log(已过滤);

但是,它不能与箭头函数()=>一起工作,因为这与它们的词法范围有关。

其他回答

var things=新对象();things.thing=新数组();thing.thing.push({place:“here”,name:“stuff”});things.thing.push({place:“there”,name:“morestuff”});things.thing.push({place:“there”,name:“morestuff”});console.log(things);函数removeDucplicate(result,id){让duplicate={};return result.filter(ele=>!duplicate[ele[id]]&&(duplicate[ele[id]]=true));}let resolverrarray=删除重复(things.thing,'place')console.log(resolverrarray);

使用Set的一个衬垫

var things=新对象();things.thing=新数组();thing.thing.push({place:“here”,name:“stuff”});things.thing.push({place:“there”,name:“morestuff”});things.thing.push({place:“there”,name:“morestuff”});//为简洁起见,将things.thing分配给myDatavar myData=things.thing;things.thing=数组.from(新集合(myData.map(JSON.stringify))).map(JSON解析);console.log(things.thing)

说明:

newSet(myData.map(JSON.stringify))使用字符串化的myData元素创建一个Set对象。Set对象将确保每个元素都是唯一的。然后,我使用array.from基于创建的集合的元素创建一个数组。最后,我使用JSON.parse将字符串化元素转换回对象。

您也可以使用地图:

const dedupThings = Array.from(things.thing.reduce((m, t) => m.set(t.place, t), new Map()).values());

完整样本:

const things = new Object();

things.thing = new Array();

things.thing.push({place:"here",name:"stuff"});
things.thing.push({place:"there",name:"morestuff"});
things.thing.push({place:"there",name:"morestuff"});

const dedupThings = Array.from(things.thing.reduce((m, t) => m.set(t.place, t), new Map()).values());

console.log(JSON.stringify(dedupThings, null, 4));

结果:

[
    {
        "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');

继续探索ES6从对象数组中删除重复项的方法:将array.prototype.filter的thisArg参数设置为new Set提供了一个不错的选择:

常量=[{地点:“这里”,名称:“东西”},{地点:“there”,名称:“morestuff”},{地点:“there”,名称:“morestuff”}];constfiltered=things.filter(函数({place,name}){const key=“${place}${name}”;回来this.has(key)&&this.add(key);},新设置);console.log(已过滤);

但是,它不能与箭头函数()=>一起工作,因为这与它们的词法范围有关。