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

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 obj = {};

for (let i = 0, len = things.thing.length; i < len; i++) {
  obj[things.thing[i]['place']] = things.thing[i];
}

things.thing = new Array();

 for (const key in obj) { 
   things.thing.push(obj[key]);
}

其他回答

我认为最好的方法是使用reduce和Map对象。这是单线解决方案。

常量数据=[{id:1,名称:“David”},{id:2,名称:“Mark”},{id:2,名称:“Lora”},{id:4,名称:“Tyler”},{id:4,名称:“Donald”},{id:5,名称:“Adrian”},{id:6,姓名:“Michael”}]constuniqueData=[…data.reduce((map,obj)=>map.set(obj.id,obj),new map()).values()];console.log(uniqueData)/*在`map.set(obj.id,obj)中`“obj.id”是键。(别担心。我们将只使用.values()方法获取值)“obj”是整个对象。*/

如果数组包含对象,则可以使用此方法删除重复的

const persons= [
      { id: 1, name: 'John',phone:'23' },
      { id: 2, name: 'Jane',phone:'23'},
      { id: 1, name: 'Johnny',phone:'56' },
      { id: 4, name: 'Alice',phone:'67' },
    ];
const unique = [...new Map(persons.map((m) => [m.id, m])).values()];

如果删除基于电话的重复项,只需将m.id替换为m.phone

const unique = [...new Map(persons.map((m) => [m.phone, m])).values()];

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'};

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

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

我知道这个问题已经有很多答案了,但请耐心等待。。。

数组中的某些对象可能具有您不感兴趣的其他财产,或者您只想查找只考虑财产子集的唯一对象。

考虑下面的数组。假设您想仅考虑propOne和propTwo来查找此数组中的唯一对象,而忽略可能存在的任何其他财产。

预期结果应仅包括第一个和最后一个对象。代码如下:

常量数组=[{propOne:“a”,propTwo:“b”,第三题:“我没有参与……”},{propOne:“a”,propTwo:“b”,someOtherProperty:“没有人关心这个…”},{propOne:'x',propTwo:'y',yetAotherJunk:“我真的一文不值”,这个:“我有一些别人没有的东西”}];常量uniques=[…新集合(array.map(x=>JSON.stringify(((o)=>({propOne:o.propOne,propTwo:o.propTwo}))(x) ))].map(JSON.parse);console.log(uniques);