简体   繁体   English

查找对象属性的数量

[英]Finding the number of object properties

I have the following JSON structure : 我有以下JSON结构

    {
        "codes":[
            {   
                    "id":"1",           
                    "code":{                
                        "fname":"S",
                        "lname":"K"

                }
            },
            {   
                    "id":"2",               
                    "code":{                
                        "fname":"M",
                        "lname":"D"                 
                }
            }
    ]
    }

I want to loop through each code and alert the number of properties within each code 我想遍历每个代码并提醒每个代码中的属性数量

        success: function (data) {               
            var x;
            for (x = 0; x < data.codes.length; x++){            
                alert(data.codes[x].id); // alerts the ID of each 'codes'
                alert(data.codes[x].code.length) // returns undefined
            }
    }

How do I do this? 我该怎么做呢?

The problem is that "code" is an object, not an array. 问题是“代码”是一个对象,而不是一个数组。 You can't get the length of an object in javascript. 您无法在javascript中获取对象的长度。 You'll have to loop through the object with a "for in" loop like below: (warning: untested). 你必须使用如下所示的“for in”循环遍历对象:(警告:未经测试)。

success: function (data) {               
        var x, codeProp, propCount;
        for (x = 0; x < data.codes.length; x++){            
            alert(data.codes[x].id); // alerts the ID of each 'codes'
            propCount = 0;
            for (codeProp in data.codes[x]) {
                if (data.codes[x].hasOwnProperty(codeProp) {
                    propCount += 1;
                }
            }

            alert(propCount) // should return number of properties in code
        }
}
if (data && rowItem.code) {

or, if you like to do it directly: 或者,如果你想直接这样做:

if (data && data.codes[x].code) {

note, the check on "data" is useless, as your code loops elements of "data" (ie if data doesn't exist, data.codes.length can only be 0, and the for loop never starts) 注意,检查“数据”是没用的,因为你的代码循环“数据”元素(即如果数据不存在,data.codes.length只能为0,for循环永远不会启动)

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

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