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

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

当前回答

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

其他回答

如果数组包含对象,则可以使用此方法删除重复的

const persons= [
      { id: 1, name: 'John',phone:'23' },
      { id: 2, name: 'Jane',phone:'23'},
      { id: 1, name: 'Johnny',phone:'56' },
      { id: 4, name: 'Alice',phone:'67' },
    ];
const unique = [...new Map(persons.map((m) => [m.id, m])).values()];

如果删除基于电话的重复项,只需将m.id替换为m.phone

const unique = [...new Map(persons.map((m) => [m.phone, m])).values()];

如果您发现需要经常基于特定字段从数组中删除重复的对象,那么创建一个可以从项目中任何位置导入的独特(数组、谓词)函数可能是值得的。这看起来像

const things = [{place:"here",name:"stuff"}, ...];
const distinctThings = distinct(things, thing => thing.place);

不同的函数可以使用上面许多好答案中给出的任何实现。最简单的方法是使用findIndex:

const distinct = (items, predicate) => items.filter((uniqueItem, index) =>
    items.findIndex(item =>
        predicate(item) === predicate(uniqueItem)) === index);

基本方法是:

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

这是我的解决方案,它基于object.prop搜索重复的对象,当找到重复的对象时,它会将array1中的值替换为array2值

function mergeSecondArrayIntoFirstArrayByProperty(array1, array2) {
    for (var i = 0; i < array2.length; i++) {
        var found = false;
        for (var j = 0; j < array1.length; j++) {
            if (array2[i].prop === array1[j].prop) { // if item exist in array1
                array1[j] = array2[i]; // replace it in array1 with array2 value
                found = true;
            }
        }
        if (!found) // if item in array2 not found in array1, add it to array1
            array1.push(array2[i]);

    }
    return array1;
}

如果您可以使用诸如下划线或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。