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;
Solution 3 (using some() method)
function _isContains(json, value) { let contains = false; Object.keys(json).some(key => { contains = typeof json[key] === 'object' ? _isContains(json[key], value) : json[key] === value; return contains; }); return contains; }
Use below code to find key is exist or not in JsonObject . has("key") method is used to find keys in JsonObject . If you are using optString("key") method to get String value then don't worry about keys are existing or not in the JsonObject . Note that you can check only root keys with has(). Get values with get().
jquery json provide several method for getting key value or check if key exists etc. In this example we will use hasOwnProperty method of json object that will help to check if key exists or not in jquery. hasOwnProperty return true if key is exists and return false if key is not exists on given javascript json.
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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With