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 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);
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 positionThe 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
Array.prototype.filter()