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

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)

其他回答

您也可以使用地图:

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

Dang,孩子们,让我们把这件事搞砸,为什么不呢?

让uniqIds={},source=〔{id:‘a’},{id:'b‘},{id:'c‘}、{id:s'b‘},{id:‘a‘};let filtered=source.filter(obj=>!uniqIds[obj.id]&&(uniqIds[obj.id]=true));console.log(已过滤);//预期:[{id:'a'},{id:'b'};

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

对于一个可读且简单的解决方案搜索者,她是我的版本:

    function removeDupplicationsFromArrayByProp(originalArray, prop) {
        let results = {};
        for(let i=0; i<originalArray.length;i++){
            results[originalArray[i][prop]] = originalArray[i];
        }
        return Object.values(results);
    }

这是一种带有Set和一些闭包的单循环方法,以防止在函数声明之外使用声明的变量,并获得简短的外观。

常量array=[{地点:“here”,名称:“stuff”,n:1},{地方:“there”,名称“morestuff”,keys=['place','name'],unique=阵列过滤器((s=>o=>(v=>!s.has(v)&&s.add(v))(keys.map(k=>o[k]).join('|')))(新设置));console.log(唯一);.作为控制台包装{最大高度:100%!重要;顶部:0;}