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

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

当前回答

如果不想指定财产列表:

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不兼容。

其他回答

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)
        }
    });
let data = [
  {
    'name': 'Amir',
    'surname': 'Rahnama'
  }, 
  {
    'name': 'Amir',
    'surname': 'Stevens'
  }
];
let non_duplicated_data = _.uniqBy(data, 'name');

要从对象数组中删除所有重复项,最简单的方法是使用过滤器:

var uniq={};var arr=[{“id”:“1”},{“id”:“2”};var arrFiltered=arr.filter(obj=>!uniq[obj.id]&&(uniq[obj.id]=true));console.log('arrFiltered',arrFiltered);

您也可以使用地图:

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

此解决方案适用于任何类型的对象,并检查数组中的每个对象(键、值)。使用临时对象作为哈希表,以查看整个object是否作为键存在。如果找到了Object的字符串表示形式,则该项将从数组中删除。

var arrOfDup=[{'id':123,'name':'name','desc':'some desc'},{“id”:125,“name”:“other name”,“desc”:“Other desc”},{“id”:123,“name”:“name”,“desc”:“some desc”},{“id”:125,“name”:“other name”,“desc”:“Other desc”},{“id”:125,“name”:“other name”,“desc”:“Other desc”}];函数removeDupes(dupArray){让temp={};let tempArray=JSON.parse(JSON.stringify(dupArray));dupArray.forEach((项,位置)=>{if(temp[JSON.stringify(item)]){tempArray.pop();}其他{temp[JSON.stringify(item)]=项;}});返回tempArray;}arrOfDup=removeDupes(arrOfDup);arrOfDup.forEach((项目,位置)=>{console.log(`${pos}位置的数组中的项是${JSON.stringify(项)}`);});