查找对象属性的数量

时间:2011-11-12 01:22:04

标签: javascript jquery json

我有以下 JSON结构

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

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

我想遍历每个代码并提醒每个代码中的属性数量

        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
            }
    }

我该怎么做?

2 个答案:

答案 0 :(得分:2)

问题是“代码”是一个对象,而不是一个数组。您无法在javascript中获取对象的长度。你必须使用如下所示的“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
        }
}

答案 1 :(得分:0)

if (data && rowItem.code) {

或者,如果你想直接这样做:

if (data && data.codes[x].code) {
注意,检查“数据”是没用的,因为你的代码循环“数据”的元素(即如果数据不存在,data.codes.length只能是0,for循环永远不会开始)< / p>