问题
I have a sharepoint column named AllLinks in which im storing array as:
[{"AllLinks":"Link9","LinkURL":"http://www.Link9.com"},
{"AllLinks":"Link6","LinkURL":"http://www.Link6.com"}]
How to check if a value exists in an array of objects and if a match is found, delete the key value pair.
For example if the value Link6 matches, delete the entry completely from the array using javascript/jquery. I tried with:
var newA = data.d.results.filter(function (item) return item.AllLinks !== x;});
but item.AllLinks
again returns the complete array itself
as AllLinks is a column in my sharepoint list.
回答1:
You can use filter function:
var a = [{"AllLinks":"Link9","LinkURL":"http://www.Link9.com"},{"AllLinks":"Link6","LinkURL":"http://www.Link6.com"}]
var newA = a.filter(function (item) {
return item.AllLinks !== "Link6";
});
回答2:
You can do this in such an easy way here:
var jsonArry = [{"AllLinks":"Link9","LinkURL":"http://www.Link9.com"},{"AllLinks":"Link6","LinkURL":"http://www.Link6.com"}];
var value = "Link6";
for(var i=0; i<jsonArry.length; i++){
if(jsonArry[i].AllLinks === value){
jsonArry.splice(i,1);
}
}
console.log(JSON.stringify(jsonArry));
If you are sure that the value
key is unique then add a break
keyword inside the for
loop within if
after you delete the object so as to prevent unnecessary loops like this,
for(var i=0; i<jsonArry.length; i++){
if(jsonArry[i].AllLinks === value){
jsonArry.splice(i,1);
break;
}
}
来源:https://stackoverflow.com/questions/45732680/how-to-check-if-a-value-exists-in-json-array-if-match-is-found-delete-the-key