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

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

当前回答

为我工作

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

其他回答

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}),{}

您还可以创建一个通用函数,该函数将根据传递给该函数的对象键过滤数组

function getUnique(arr, comp) {

  return arr
   .map(e => e[comp])
   .map((e, i, final) => final.indexOf(e) === i && i)  // store the keys of the unique objects
   .filter(e => arr[e]).map(e => arr[e]); // eliminate the dead keys & store unique objects

 }

你可以这样调用函数,

getUnique(things.thing,'name') // to filter on basis of name

getUnique(things.thing,'place') // to filter on basis of place

您可以使用Set和Filter方法来实现这一点,

变量arrObj=[{a: 1中,b: 2个}, {a: 1中,b: 1个}, {a: 1中,b: 2个}];var duplicateRemove=新集合();var distinctArObj=arrObj.filter((obj)=>{if(duplicateRemove.has(JSON.stringify(obj)))返回false;duplicateRemove.add(JSON.stringify(obj));返回true;});console.log(distinctArObj);

Set是一个唯一的基元类型集合,因此不会直接作用于对象,但是JSON.stringify会将其转换为基元类型,即String,因此我们可以过滤。

如果您希望仅基于某个特定的键(例如key)删除重复项,可以将JSON.stringify(obj)替换为obj.key

为我工作

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

我有一个完全相同的要求,即基于单个字段上的重复项删除数组中的重复对象。我在这里找到了代码:Javascript:从对象数组中删除重复项

所以在我的示例中,我要从数组中删除具有重复licenseNum字符串值的任何对象。

var arrayWithDuplicates = [
    {"type":"LICENSE", "licenseNum": "12345", state:"NV"},
    {"type":"LICENSE", "licenseNum": "A7846", state:"CA"},
    {"type":"LICENSE", "licenseNum": "12345", state:"OR"},
    {"type":"LICENSE", "licenseNum": "10849", state:"CA"},
    {"type":"LICENSE", "licenseNum": "B7037", state:"WA"},
    {"type":"LICENSE", "licenseNum": "12345", state:"NM"}
];

function removeDuplicates(originalArray, prop) {
     var newArray = [];
     var lookupObject  = {};

     for(var i in originalArray) {
        lookupObject[originalArray[i][prop]] = originalArray[i];
     }

     for(i in lookupObject) {
         newArray.push(lookupObject[i]);
     }
      return newArray;
 }

var uniqueArray = removeDuplicates(arrayWithDuplicates, "licenseNum");
console.log("uniqueArray is: " + JSON.stringify(uniqueArray));

结果:

uniqueArray是:

[{"type":"LICENSE","licenseNum":"10849","state":"CA"},
{"type":"LICENSE","licenseNum":"12345","state":"NM"},
{"type":"LICENSE","licenseNum":"A7846","state":"CA"},
{"type":"LICENSE","licenseNum":"B7037","state":"WA"}]