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

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

当前回答

可以将Object.values()与Array.prototype.reduce()结合使用:

const things=新对象();things.thing=新数组();thing.thing.push({place:“here”,name:“stuff”});things.thing.push({place:“there”,name:“morestuff”});things.thing.push({place:“there”,name:“morestuff”});constresult=Object.values(things.thing.reduce((a,c)=>(a[`${c.place}${c.name}`]=c,a),{}));console.log(结果);.作为控制台包装{最大高度:100%!重要;顶部:0;}

其他回答

这是如何从对象数组中删除重复性的简单方法。

我经常处理数据,这对我很有用。

const data = [{name: 'AAA'}, {name: 'AAA'}, {name: 'BBB'}, {name: 'AAA'}];
function removeDuplicity(datas){
    return datas.filter((item, index,arr)=>{
    const c = arr.map(item=> item.name);
    return  index === c.indexOf(item.name)
  })
}

console.log(removeDuplicity(data))

将打印到控制台:

[[object Object] {
name: "AAA"
}, [object Object] {
name: "BBB"
}]

如果您严格希望基于一个属性删除重复项,则可以基于place属性将数组缩减为和对象,因为对象只能具有唯一的键,因此只需获取值即可返回数组:

const unique = Object.values(things.thing.reduce((o, t) => ({ ...o, [t.place]: t }), {}))

让事情变得简单。幻想是好的,但不可读的代码是无用的。享受:-)

变量a=[{执行ID:6873702,largePhotoCircle:null,姓名:“John A.Cuomo”,photoURL:null,Primary公司:“VSE CORP”,primary职务:“首席执行官、总裁和董事”},{执行ID:6873702,largePhotoCircle:null,姓名:“John A.Cuomo”,photoURL:null,Primary公司:“VSE CORP”,primary职务:“首席执行官、总裁和董事”},{执行ID:6873703,largePhotoCircle:null,姓名:“John A.Cuomo”,photoURL:null,Primary公司:“VSE CORP”,primaryTitle:“首席执行官、总裁和董事”,}];函数filterDuplicate(myArr,prop){//格式-(1)//返回myArr.filter((obj,pos,arr)=>{//return arr.map(mapObj=>mapObj[prop]).indexOf(obj[pprop])==pos;// });//格式-(2)var res={};var resArr=[];for(myArr的var elem){res[elem.executiveId]=elem;}for(let[index,elem]of Object.entries(res)){资源推送(elem);}返回resArr;}let finalRes=filterDuplicate(a,“executiveId”);console.log(“finalResults:”,finalRes);

 npm i lodash

 let non_duplicated_data = _.uniqBy(pendingDeposits, v => [v.stellarAccount, v.externalTransactionId].join());

如果您正在使用Lodash库,也可以使用以下函数。它应该删除重复的对象。

var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
_.uniqWith(objects, _.isEqual);