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

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

当前回答

在这里,我找到了一个使用reduce方法从对象数组中删除重复项的简单解决方案。我正在根据对象的位置键过滤元素

常量med=[{name:“name1”,位置:“left”},{name:“name2”,位置:“right”},{name:“name3”,位置:“left”},{name:“name4”,位置:“right”},{name:“name5”,位置:“left”},{name:“name6”,位置:“left1”}]常量arr=[];med.reduce((acc,curr)=>{如果(acc.indexOf(当前位置)==-1){acc.push(当前位置);arr.push(当前);}返回acc;}, [])控制台日志(arr)

其他回答

继续探索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(已过滤);

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

这里有另一种技术,可以找到重复的数量,并轻松地从数据对象中删除它。“dupsCount”是重复文件数。首先对数据进行排序,然后删除。它将为您提供最快的重复删除。

  dataArray.sort(function (a, b) {
            var textA = a.name.toUpperCase();
            var textB = b.name.toUpperCase();
            return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
        });
        for (var i = 0; i < dataArray.length - 1; ) {
            if (dataArray[i].name == dataArray[i + 1].name) {
                dupsCount++;
                dataArray.splice(i, 1);
            } else {
                i++;
            }
        }

这里是ES6的解决方案,您只想保留最后一项。该解决方案功能强大,符合Airbnb风格。

const things = {
  thing: [
    { place: 'here', name: 'stuff' },
    { place: 'there', name: 'morestuff1' },
    { place: 'there', name: 'morestuff2' }, 
  ],
};

const removeDuplicates = (array, key) => {
  return array.reduce((arr, item) => {
    const removed = arr.filter(i => i[key] !== item[key]);
    return [...removed, item];
  }, []);
};

console.log(removeDuplicates(things.thing, 'place'));
// > [{ place: 'here', name: 'stuff' }, { place: 'there', name: 'morestuff2' }]

可以将Object.values()与Array.prototype.reduce()结合使用:

const things=新对象();things.thing=新数组();thing.thing.push({place:“here”,name:“stuff”});things.thing.push({place:“there”,name:“morestuff”});things.thing.push({place:“there”,name:“morestuff”});constresult=Object.values(things.thing.reduce((a,c)=>(a[`${c.place}${c.name}`]=c,a),{}));console.log(结果);.作为控制台包装{最大高度:100%!重要;顶部:0;}

基本方法是:

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