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

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魔术在一条线上。。。在那时候可读!

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

其他回答

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

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

如果不想指定财产列表:

function removeDuplicates(myArr) {
  var props = Object.keys(myArr[0])
  return myArr.filter((item, index, self) =>
    index === self.findIndex((t) => (
      props.every(prop => {
        return t[prop] === item[prop]
      })
    ))
  )
}

再见!与IE11不兼容。

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]));
};
function filterDuplicateQueries(queries){
    let uniqueQueries = [];
     queries.forEach((l, i)=>{
        let alreadyExist = false;
        if(uniqueQueries.length>0){
            uniqueQueries.forEach((k, j)=>{
                if(k.query == l.query){
                    alreadyExist = true;
                }
            });
        }
        if(!alreadyExist){
           uniqueQueries.push(l)
        }
    });

你听说过洛达什图书馆吗?当您不想将逻辑应用于代码时,我建议您使用此实用程序,并使用已优化且可靠的现有代码。

考虑制作一个这样的数组

things.thing.push({place:"utopia",name:"unicorn"});
things.thing.push({place:"jade_palace",name:"po"});
things.thing.push({place:"jade_palace",name:"tigress"});
things.thing.push({place:"utopia",name:"flying_reindeer"});
things.thing.push({place:"panda_village",name:"po"});

注意,如果您想保持一个属性的唯一性,您可以使用lodash库来实现这一点。在这里,您可以使用_.uniqBy

.uniqBy(数组,[iteratee=.identity])

此方法类似于_.uniq(它返回一个数组的无重复版本,其中只保留每个元素的第一次出现),只是它接受iterate,iterate为数组中的每个元素调用,以生成计算唯一性的标准。

因此,例如,如果要返回具有唯一属性“place”的数组

_.uniqBy(things.thing,'place')

同样,如果您希望唯一属性为“name”

_.uniqBy(things.thing,'name')

希望这有帮助。

干杯