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

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

当前回答

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

其他回答

es6魔术在一条线上。。。在那时候可读!

// returns the union of two arrays where duplicate objects with the same 'prop' are removed
const removeDuplicatesWith = (a, b, prop) => {
  a.filter(x => !b.find(y => x[prop] === y[prop]));
};

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

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

考虑下面的数组。假设您想仅考虑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);

基本方法是:

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]);
}

您也可以使用地图:

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

另一种方法是使用reduce函数,并使用一个新数组作为累加器。如果累加器数组中已经有一个同名的对象,那么不要将其添加到那里。

let list = things.thing;
list = list.reduce((accumulator, thing) => {
    if (!accumulator.filter((duplicate) => thing.name === duplicate.name)[0]) {
        accumulator.push(thing);
    }
    return accumulator;
}, []);
thing.things = list;

我添加了这个答案,因为我找不到与InternetExplorer11兼容的好的、可读的es6解决方案(我使用babel来处理箭头函数)。问题是IE11没有没有polyfill的Map.values()或Set.values)。出于同样的原因,我使用filter()[0]来获取第一个元素,而不是find()。