亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

javascript - One is an array and the other is an object. How to compare and remove duplicates?
僅有的幸福
僅有的幸福 2017-07-05 10:53:25
0
4
941
var arr=[{'id':1,'name':1},{'id':2,name:2},{'id':3,'name':3}];
var obj = {'id':2,'name':2};

How to compare arr and obj? After discovering that id2 is repeated, remove the array object id:2 of arr and generate a new array?

僅有的幸福
僅有的幸福

reply all(4)
給我你的懷抱

Use the array filter to filter to generate a new array.
In addition, the second part of the array in the question 'id:2'has a grammatical error and the quotation marks are in the wrong position

var res = arr.filter(function(e){
    return e.id!=obj.id
})

The following is my imagination: What if the key point of the question is that the key-value pairs are repeated before filtering... (I may be overthinking)

Considering that you may also want to ensure that the key-value pairs of the elements in the array must be exactly the same as the key-value pairs of obj: you can consider this

var arr=[{'id':1,'name':1},{id:2,name:3},{'id':3,'name':3}];
var arr2=[{'id':1,'name':1},{id:2,name:2},{'id':3,'name':3}];
var obj = {'id':2,'name':2};
var res = arr.filter(function(e){//
  var result = true; //作為過濾標(biāo)識
  for(var key in obj){//遍歷obj的鍵值
      if(e[key]!=obj[key]){//如果出現(xiàn)鍵值相同當(dāng)值不同,就不算重復(fù)
           result = true;
          break;
      }
      //如果上面條件不通過,那就表示鍵值重復(fù)
      result = false;
   }//遍歷到最后,如果鍵值都重復(fù),那result肯定是false,否則必然出現(xiàn)result=true的情況
   return result;
});
var res2 = arr.filter(function(e){
  var result = true; 
  for(var key in obj){
      if(e[key]!=obj[key]){
           result = true;
          break;
      }
      result = false;
   }
   return result;
});
洪濤
var newArr = arr.filter(item => item.id !== obj.id)
迷茫
var arr=[{'id':1,'name':1},{'id':2,name:2},{'id':3,'name':3}];
var obj = {'id':2,'name':2};

var index = -1;
for (let i = 0; i < arr.length; i++) {
    let flag = false;
    for (let item in obj) {
        if (obj[item] !== arr[i][item]) {
            flag = true;
        }
    }
    if (!flag) {
        index = i;
    }
}
console.log(index);
arr.splice(index,index>0);
console.log(arr);
為情所困

Array.prototype.filter()

var arr=[{'id':1,'name':1},{'id':2,name:2},{'id':3,'name':3}];
var obj = {'id':2,'name':2};
var newArray = arr.filter((obj_)=>(obj_.id !== obj.id))
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template