Ivan Ivan - 22 days ago 6
Javascript Question

Check whether a value exists in JSON object

I have the next JSON:


var JSONObject = {"animals": [{name:"cat"}, {name:"dog"}]};


What is the best way to know if the "dog" value exists in the JSON object?

Thanks.

Solution 1

var JSONObject = {"animals": [{name:"cat"}, {name:"dog"}]};
...
for (i=0; i < JSONObject.animals.length; i++) {
if (JSONObject.animals[i].name == "dog")
return true;
}
return false;


Solution 2 (JQuery)

var JSONObject = {"animals": [{name:"cat"}, {name:"dog"}]};
...
$.map(JSONObject.animals, function(elem, index) {
if (elem.name == "dog")
return true;
});
return false;

Answer
var JSON = [{"name":"cat"}, {"name":"dog"}];

The JSON variable refers to an array of object with one property called "name". I don't know of the best way but this is what I do?

var hasMatch =false;

for (var index = 0; index < JSON.length; ++index) {

 var animal = JSON[index];

 if(animal.Name == "dog"){
   hasMatch = true;
   break;
 }
}
Comments