检查JSON对象中是否存在值 [英] Check whether a value exists in JSON object
本文介绍了检查JSON对象中是否存在值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有下一个JSON:
I have the next JSON:
var JSONObject = {"animals": [{name:"cat"}, {name:"dog"}]};
知道JSON对象中是否存在dog值的最佳方法是什么?
What is the best way to know if the "dog" value exists in the JSON object?
谢谢。
解决方案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;
解决方案2(JQuery)
var JSONObject = {"animals": [{name:"cat"}, {name:"dog"}]};
...
$.map(JSONObject.animals, function(elem, index) {
if (elem.name == "dog")
return true;
});
return false;
解决方案3(使用some()方法)
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;
}
推荐答案
var JSON = [{"name":"cat"}, {"name":"dog"}];
JSON变量引用具有一个名为name的属性的对象数组。
我不知道最好的方法,但这就是我的工作?
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;
}
}
这篇关于检查JSON对象中是否存在值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文