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

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

当前回答

我们可以利用Javascript的Set对象和Array的Filter函数:例如:

//示例阵列const arr=[{id:“1”},{id:“2”};//收集要过滤元素的唯一元素Id。constuniqIds=arr.reduce((id,el)=>ids.add(el.id),new Set());//过滤出uniq元素。const uniqElements=arr.filter((el)=>uniqIds.delete(el.id));console.log(uniqElements);

其他回答

如果不想指定财产列表:

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

您可以将数组对象转换为字符串,以便对其进行比较,将字符串添加到集合中,以便自动删除可比较的重复项,然后将每个字符串转换回对象。

它可能不像其他答案那样有表现力,但它是可读的。

const things = {};

things.thing = [];
things.thing.push({place:"here",name:"stuff"});
things.thing.push({place:"there",name:"morestuff"});
things.thing.push({place:"there",name:"morestuff"});

const uniqueArray = (arr) => {

  const stringifiedArray = arr.map((item) => JSON.stringify(item));
  const set = new Set(stringifiedArray);

  return Array.from(set).map((item) => JSON.parse(item));
}

const uniqueThings = uniqueArray(things.thing);

console.log(uniqueThings);

我认为最好的方法是使用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”是整个对象。*/

让myData=[{place:“here”,name:“stuff”},{地点:“there”,名称:“morestuff”},{地点:“there”,名称:“morestuff”}];let q=[…new Map(myData.Map(obj=>[JSON.stringify(obj),obj]).values()];控制台日志(q)

一个使用ES6和new Map()的命令行。

// assign things.thing to myData
let myData = things.thing;

[...new Map(myData.map(obj => [JSON.stringify(obj), obj])).values()];

详细信息:-

对数据列表执行.map()并将每个单独的对象转换为[key,value]对数组(长度=2),第一个元素(key)将是对象的字符串化版本,第二个元素(value)将是一个对象本身。将上述创建的数组列表添加到新的Map()中会将键作为字符串化对象,任何相同的键添加都会导致覆盖现有的键。使用.values()将为MapIterator提供Map中的所有值(在本例中为obj)最后,传播。。。运算符为新数组提供上述步骤中的值。

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

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