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

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

当前回答

如果您正在使用Lodash库,也可以使用以下函数。它应该删除重复的对象。

var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
_.uniqWith(objects, _.isEqual);

其他回答

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

const uniqueElements = (arr, fn) => arr.reduce((acc, v) => {
    if (!acc.some(x => fn(v, x))) { acc.push(v); }
    return acc;
}, []);

const stuff = [
    {place:"here",name:"stuff"},
    {place:"there",name:"morestuff"},
    {place:"there",name:"morestuff"},
];

const unique = uniqueElements(stuff, (a,b) => a.place === b.place && a.name === b.name );
//console.log( unique );

[{
    "place": "here",
    "name": "stuff"
  },
  {
    "place": "there",
    "name": "morestuff"
}]

基本方法是:

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

来源

JSFiddle公司

这将在不传递任何键的情况下删除重复对象。

uniqueArray=a=>[…new Set(.map(o=>JSON.stringify(o))].map(s=>JSON.parse(s));var objects=[{'x':1,'y':2},{'x':2,'y':1},{'x':1,'y':2}];var unique=uniqueArray(对象);console.log(“原始对象”,对象);console.log(“唯一”,唯一);

uniqueArray = a => [...new Set(a.map(o => JSON.stringify(o)))].map(s => JSON.parse(s));

    var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];

    var unique = uniqueArray(objects);
    console.log(objects);
    console.log(unique);