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

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

当前回答

另一个选项是创建一个自定义indexOf函数,该函数比较每个对象所选属性的值,并将其包装在reduce函数中。

var uniq = redundant_array.reduce(function(a,b){
      function indexOfProperty (a, b){
          for (var i=0;i<a.length;i++){
              if(a[i].property == b.property){
                   return i;
               }
          }
         return -1;
      }

      if (indexOfProperty(a,b) < 0 ) a.push(b);
        return a;
    },[]);

其他回答

这里是ES6的解决方案,您只想保留最后一项。该解决方案功能强大,符合Airbnb风格。

const things = {
  thing: [
    { place: 'here', name: 'stuff' },
    { place: 'there', name: 'morestuff1' },
    { place: 'there', name: 'morestuff2' }, 
  ],
};

const removeDuplicates = (array, key) => {
  return array.reduce((arr, item) => {
    const removed = arr.filter(i => i[key] !== item[key]);
    return [...removed, item];
  }, []);
};

console.log(removeDuplicates(things.thing, 'place'));
// > [{ place: 'here', name: 'stuff' }, { place: 'there', name: 'morestuff2' }]

我有一个完全相同的要求,即基于单个字段上的重复项删除数组中的重复对象。我在这里找到了代码: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"}]

这是我的解决方案,它基于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;
}

让事情变得简单。幻想是好的,但不可读的代码是无用的。享受:-)

变量a=[{执行ID:6873702,largePhotoCircle:null,姓名:“John A.Cuomo”,photoURL:null,Primary公司:“VSE CORP”,primary职务:“首席执行官、总裁和董事”},{执行ID:6873702,largePhotoCircle:null,姓名:“John A.Cuomo”,photoURL:null,Primary公司:“VSE CORP”,primary职务:“首席执行官、总裁和董事”},{执行ID:6873703,largePhotoCircle:null,姓名:“John A.Cuomo”,photoURL:null,Primary公司:“VSE CORP”,primaryTitle:“首席执行官、总裁和董事”,}];函数filterDuplicate(myArr,prop){//格式-(1)//返回myArr.filter((obj,pos,arr)=>{//return arr.map(mapObj=>mapObj[prop]).indexOf(obj[pprop])==pos;// });//格式-(2)var res={};var resArr=[];for(myArr的var elem){res[elem.executiveId]=elem;}for(let[index,elem]of Object.entries(res)){资源推送(elem);}返回resArr;}let finalRes=filterDuplicate(a,“executiveId”);console.log(“finalResults:”,finalRes);

这是我的两分钱。如果您知道财产的顺序相同,则可以将元素串接起来,并从数组中删除重复项,然后再次解析数组。类似于:

var things=新对象();things.thing=新数组();thing.thing.push({place:“here”,name:“stuff”});things.thing.push({place:“there”,name:“morestuff”});things.thing.push({place:“there”,name:“morestuff”});let-stringified=things.thing.map(i=>JSON.sringify(i));let unique=stringified.filter((k,idx)=>stringified.indexOf(k)==idx).map(j=>JSON.parse(j))console.log(唯一);