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

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

当前回答

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

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

其他回答

ES6一个衬垫在这里

设arr=[{id:1,名称:“sravan ganji”},{id:2,name:“pinky”},{id:4,名称:“mammu”},{id:3,名称:“avy”},{id:3,名称:“rashni”},];console.log(Object.values(arr.reduce((acc,cur)=>Object.assign(acc、{[cur.id]:cur}),{}

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

您也可以使用地图:

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

来点es6魔法怎么样?

obj.arr = obj.arr.filter((value, index, self) =>
  index === self.findIndex((t) => (
    t.place === value.place && t.name === value.name
  ))
)

参考URL

更通用的解决方案是:

const uniqueArray = obj.arr.filter((value, index) => {
  const _value = JSON.stringify(value);
  return index === obj.arr.findIndex(obj => {
    return JSON.stringify(obj) === _value;
  });
});

使用上述属性策略而不是JSON.stringify:

const isPropValuesEqual = (subject, target, propNames) =>
  propNames.every(propName => subject[propName] === target[propName]);

const getUniqueItemsByProperties = (items, propNames) => 
  items.filter((item, index, array) =>
    index === array.findIndex(foundItem => isPropValuesEqual(foundItem, item, propNames))
  );

如果希望propNames属性为数组或值,可以添加包装器:

const getUniqueItemsByProperties = (items, propNames) => {
  const propNamesArray = Array.from(propNames);

  return items.filter((item, index, array) =>
    index === array.findIndex(foundItem => isPropValuesEqual(foundItem, item, propNamesArray))
  );
};

允许getUniqueItemsByProperty('a')和getUniqueItemsByProperty(['a']);

Stackblitz示例

解释

首先了解使用的两种方法:过滤器,findIndex接下来,让你的想法让你的两个对象相等,并记住这一点。如果某个东西满足我们刚刚想到的标准,我们可以将其检测为复制品,但它的位置不在具有该标准的对象的第一个实例处。因此,我们可以使用上述标准来确定某个东西是否是重复的。

function filterDuplicateQueries(queries){
    let uniqueQueries = [];
     queries.forEach((l, i)=>{
        let alreadyExist = false;
        if(uniqueQueries.length>0){
            uniqueQueries.forEach((k, j)=>{
                if(k.query == l.query){
                    alreadyExist = true;
                }
            });
        }
        if(!alreadyExist){
           uniqueQueries.push(l)
        }
    });