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
806
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; //作为过滤标识 for(var key in obj){//遍历obj的键值 if(e[key]!=obj[key]){//如果出现键值相同当值不同,就不算重复 result = true; break; } //如果上面条件不通过,那就表示键值重复 result = false; }//遍历到最后,如果键值都重复,那result肯定是false,否则必然出现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
          About us Disclaimer Sitemap
          php.cn:Public welfare online PHP training,Help PHP learners grow quickly!