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

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

当前回答

var things=新对象();things.thing=新数组();thing.thing.push({place:“here”,name:“stuff”});things.thing.push({place:“there”,name:“morestuff”});things.thing.push({place:“there”,name:“morestuff”});console.log(things);函数removeDucplicate(result,id){让duplicate={};return result.filter(ele=>!duplicate[ele[id]]&&(duplicate[ele[id]]=true));}let resolverrarray=删除重复(things.thing,'place')console.log(resolverrarray);

其他回答

向列表中再添加一个。将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')

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

如果需要基于对象中的多个财产的唯一数组,可以通过映射和组合对象的财产来实现。

    var hash = array.map(function(element){
        var string = ''
        for (var key in element){
            string += element[key]
        }
        return string
    })
    array = array.filter(function(element, index){
        var string = ''
        for (var key in element){
            string += element[key]
        }
        return hash.indexOf(string) == index
    })

使用Set的一个衬垫

var things=新对象();things.thing=新数组();thing.thing.push({place:“here”,name:“stuff”});things.thing.push({place:“there”,name:“morestuff”});things.thing.push({place:“there”,name:“morestuff”});//为简洁起见,将things.thing分配给myDatavar myData=things.thing;things.thing=数组.from(新集合(myData.map(JSON.stringify))).map(JSON解析);console.log(things.thing)

说明:

newSet(myData.map(JSON.stringify))使用字符串化的myData元素创建一个Set对象。Set对象将确保每个元素都是唯一的。然后,我使用array.from基于创建的集合的元素创建一个数组。最后,我使用JSON.parse将字符串化元素转换回对象。

可以将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;}