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;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…