Tuesday, June 7, 2011

How to check an array item exist or not in the json array based on the item property value in javascript

In my current project i am working more with jquery and json.In this project i had a requirement to find the json object exist or not in the json array based on the item property value.I had googled a bit and did not find the answer.

Then i wrote a prototype method to find the json object exist or not.

Array.prototype.containsJsonObj = function(name,value) {
var isExists=false;
$.each(this,function(){
if(this[name]==value){
isExists=true;
return false;
}});
return isExists;
};


Below is the json array

var jsonArray=[{"firstName":"John","lastName":"Doe","age": 23 },
{ "firstName":"Mary","lastName" :"Smith","age": 32 }]

we can check whether the array item exist or not as shown below

if(jsonArray.containsJsonObj("firstName","John"))
{
//if it exists enter into this loop
}
else
{
//if it does not exist enter into this loop
}

No comments:

Post a Comment