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

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

其他回答

您还可以创建一个通用函数,该函数将根据传递给该函数的对象键过滤数组

function getUnique(arr, comp) {

  return arr
   .map(e => e[comp])
   .map((e, i, final) => final.indexOf(e) === i && i)  // store the keys of the unique objects
   .filter(e => arr[e]).map(e => arr[e]); // eliminate the dead keys & store unique objects

 }

你可以这样调用函数,

getUnique(things.thing,'name') // to filter on basis of name

getUnique(things.thing,'place') // to filter on basis of place

简单高效的解决方案,运行时间比现有的70多个答案更好:

const ids = array.map(o => o.id)
const filtered = array.filter(({id}, index) => !ids.includes(id, index + 1))

例子:

const arr=[{id:1,名称:“one”},{id:2,名称:‘two’},{id:1,姓名:‘one’}]常量id=arr.map(o=>o.id)constfiltered=arr.filter(({id},索引)=>!ids.includes(id,索引+1))console.log(已过滤)

工作原理:

Array.filter()通过检查先前映射的id数组是否包含当前id来删除所有重复的对象({id}仅将对象销毁为其id)。为了只过滤出实际的重复项,它使用了Array.includes()的第二个参数fromIndex,索引为+1,这将忽略当前对象和所有先前对象。

由于过滤器回调方法的每一次迭代都将只搜索从当前索引+1开始的数组,这也大大减少了运行时间,因为只有以前未过滤的对象才会被检查。

这显然也适用于任何其他不称为id的键、多个键甚至所有键。

继续探索ES6从对象数组中删除重复项的方法:将array.prototype.filter的thisArg参数设置为new Set提供了一个不错的选择:

常量=[{地点:“这里”,名称:“东西”},{地点:“there”,名称:“morestuff”},{地点:“there”,名称:“morestuff”}];constfiltered=things.filter(函数({place,name}){const key=“${place}${name}”;回来this.has(key)&&this.add(key);},新设置);console.log(已过滤);

但是,它不能与箭头函数()=>一起工作,因为这与它们的词法范围有关。

如果您不介意以后对唯一数组进行排序,这将是一个有效的解决方案:

things.thing
  .sort(((a, b) => a.place < b.place)
  .filter((current, index, array) =>
    index === 0 || current.place !== array[index - 1].place)

这样,您只需将当前元素与数组中的前一个元素进行比较。在过滤之前排序一次(O(n*log(n))比在整个数组中搜索每个数组元素的重复项(O(n²))要便宜。

向列表中再添加一个。将ES6和Array.reduce与Array.find一起使用。在此示例中,根据guid属性筛选对象。

let filtered = array.reduce((accumulator, current) => {
  if (! accumulator.find(({guid}) => guid === current.guid)) {
    accumulator.push(current);
  }
  return accumulator;
}, []);

扩展此选项以允许选择属性并将其压缩为一行:

const uniqify = (array, key) => array.reduce((prev, curr) => prev.find(a => a[key] === curr[key]) ? prev : prev.push(curr) && prev, []);

要使用它,请将对象数组和要进行重复数据消除的键的名称作为字符串值传递:

const result = uniqify(myArrayOfObjects, 'guid')