Javascript 我如何查看一个大的 JSON 对象是否包含一个值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3021206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how do i see if a big JSON object contains a value?
提问by Haroldo
I'm using PHP to json encode a massive multi-dimensional array of events, so i get something like this:
我正在使用 PHP 对大量的多维事件数组进行 json 编码,所以我得到如下信息:
var ents = {"7":{"event_id":"7","nn":"The Whisky Drifters","nn_url":"the-whisky-drifters",
"venue":"The Grain Barge","date_num":"2010-06-11","date_txt":"Friday 11th June",
"gig_club":"1","sd":"A New Acoustic String Band...","ven_id":"44",
"art":0},"15":{"event_id":"15","nn":"Bass Kitchen","nn_url":"bass-kitchen",
"venue":"Timbuk2","date_num":"2010-06-11","date_txt":"Friday 11th June",
"gig_club":"2","sd":"Hexadecimal \/ DJ Derek \/ Id","ven_id":"21",
"art":1},
the first dimension is the id, see
第一个维度是id,见
var ents = {"7":{
So it's possible to get the ids without examining the nested objects...
因此可以在不检查嵌套对象的情况下获取 id...
What's the fastest, most efficient way to check if my JSON contains an id?
检查我的 JSON 是否包含 id 的最快、最有效的方法是什么?
回答by CMS
You can use the hasOwnPropertymethod:
您可以使用以下hasOwnProperty方法:
if (ents.hasOwnProperty('7')) {
//..
}
This method checks if the object contains the specified property regardless of its value.
此方法检查对象是否包含指定的属性,而不管其值如何。
Is faster than the inoperator because it doesn't checks for inherited properties.
比in运算符更快,因为它不检查继承的属性。
回答by RoToRa
Additionally to what CMS said: If you need all properties, you can loop over the porperties with for ... in:
除了 CMS 所说的:如果您需要所有属性,您可以使用以下命令遍历属性for ... in:
for (prop in ents) {
alert(prop); // Shows "7", "15", etc.
// Accessing the sub-object:
alert(ents[prop].nn); // Shows the names of each event
}
Also that isn't a "multi-dimensional array". It's an object (with more nested objects).
这也不是“多维数组”。它是一个对象(具有更多嵌套对象)。
回答by Ayaz Alavi
yes it is possible but you have to loop through complete json object on client side.
是的,这是可能的,但您必须在客户端遍历完整的 json 对象。
var JSONobj = ents, yourid;
for(key in JSONobj)
{
if(((typeof key) == 'number') && key==yourid )
alert(key);
}
if you are using jQuery then you can use $.each method to fetchng keys from jsonObject
如果您使用的是 jQuery,那么您可以使用 $.each 方法从 jsonObject 中获取键
var JSONobj = ents, yourid;
$.each(JSONobj, function(key, value){
if(((typeof key) == 'number') && key==yourid )
alert(key);
//ids.push(key);
});
回答by Jurijs Kastanovs
Just use myObject.has("keyName"). This is what really works.
只需使用myObject.has("keyName"). 这才是真正有效的方法。

