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

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

当前回答

任何对象数组的泛型:

/**
* Remove duplicated values without losing information
*/
const removeValues = (items, key) => {
  let tmp = {};

  items.forEach(item => {
    tmp[item[key]] = (!tmp[item[key]]) ? item : Object.assign(tmp[item[key]], item);
  });
  items = [];
  Object.keys(tmp).forEach(key => items.push(tmp[key]));

  return items;
}

希望这对任何人都有帮助。

其他回答

TypeScript函数将数组过滤到其唯一元素,其中唯一性由给定的谓词函数决定:

function uniqueByPredicate<T>(arr: T[], predicate: (a: T, b: T) => boolean): T[] {
  return arr.filter((v1, i, a) => a.findIndex(v2 => predicate(v1, v2)) === i);
}

不打字员:

function uniqueByPredicate(arr, predicate) {
  return l.filter((v1, i, a) => a.findIndex(v2 => predicate(v1, v2)) === i);
}

另一种方法是使用reduce函数,并使用一个新数组作为累加器。如果累加器数组中已经有一个同名的对象,那么不要将其添加到那里。

let list = things.thing;
list = list.reduce((accumulator, thing) => {
    if (!accumulator.filter((duplicate) => thing.name === duplicate.name)[0]) {
        accumulator.push(thing);
    }
    return accumulator;
}, []);
thing.things = list;

我添加了这个答案,因为我找不到与InternetExplorer11兼容的好的、可读的es6解决方案(我使用babel来处理箭头函数)。问题是IE11没有没有polyfill的Map.values()或Set.values)。出于同样的原因,我使用filter()[0]来获取第一个元素,而不是find()。

如果您可以使用诸如下划线或lodash之类的Javascript库,我建议查看它们库中的_.uniq函数。来自lodash:

_.uniq(array, [isSorted=false], [callback=_.identity], [thisArg])

基本上,您传入数组,这里是一个对象文本,然后传入要在原始数据数组中删除重复项的属性,如下所示:

var data = [{'name': 'Amir', 'surname': 'Rahnama'}, {'name': 'Amir', 'surname': 'Stevens'}];
var non_duplidated_data = _.uniq(data, 'name'); 

更新:Lodash现在也引入了.uniqBy。

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]));
};
str =[
{"item_id":1},
{"item_id":2},
{"item_id":2}
]

obj =[]
for (x in str){
    if(check(str[x].item_id)){
        obj.push(str[x])
    }   
}
function check(id){
    flag=0
    for (y in obj){
        if(obj[y].item_id === id){
            flag =1
        }
    }
    if(flag ==0) return true
    else return false

}
console.log(obj)

str是一个对象数组。存在具有相同值的对象(这里是一个小示例,有两个对象的item_id与2相同)。check(id)是一个函数,用于检查是否存在任何具有相同itemid的对象。如果存在,则返回false,否则返回true。根据该结果,将对象推入新的数组obj上述代码的输出为[{“item_id”:1},{“item_id”:2}]