How to check if a value exists in json array? If match is found, delete the key value pair

梦想与她 提交于 2019-12-12 04:37:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!