简体   繁体   English

计算父JSON对象内的对象

[英]Count Objects inside parent JSON Object

JSON JSON

{
    "AA1 1AA":{
        "ExchangeCode":"XXX",
        "ExchangeName":"XXXXX",
        "Options":{
            "10":{
                "Preference":"Preference 1",
                "Option 1":123,
                "Option 2":1234,
                "Option 3":1234,
                "Option 4":1234
            },
            "20":{ .........

            }
        }
    }
}

The AA1 1AA is a postcode and so changes with every request. AA1 1AA是一个邮政编码,因此随着每个请求而变化。

jQuery jQuery的

// var count = 0; is declared in document ready function so that it's global

// JSON response from server is stored in 'data'

 var key, count = 0;
 for (key in data.Options) {
     if(data.Options.hasOwnProperty(key)) {
         count++;
     }
 }

The result is just undefined 结果是undefined

You seem to want to get the first element. 你似乎想得到第一个元素。 You may do this : 你可以这样做:

 var count = 0;
 for (var k in data) { // only simple cross browser way to get the first property
     var obj = data[k];
     for (var key in obj) {
         count++;
     }
     break; // no need to go further, we have counted in "AA1 1AA" 
 }

Note that I removed the hasOwnProperty check : it's totally useless for JSON parsed data. 请注意,我删除了hasOwnProperty检查:它对于JSON解析数据完全没用。

Note that modern browsers have additional facilities, like Object.keys 请注意,现代浏览器具有其他功能,如Object.keys

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM