techlead
techlead

Reputation: 779

JSON - Return Property Count

JSON structure:

{
    "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, count=0;
        for (x = 0; x < data.codes.length; x++){
            for (property in data.codes[x].code) {
                count++;
                alert(count);                           
            }                   
        }       
    }

The above works BUT it returns 4 as the count. It should return 2 for each code.

Upvotes: 0

Views: 2209

Answers (1)

PiTheNumber
PiTheNumber

Reputation: 23542

You problem is that code is an object not an array. You can loop over the properties of an object like this:

success: function(data){
    var x;
    for (x = 0; x < data.codes.length; x++){
        var count = 0;
        for (property in data.codes[x].code) {
            count++;
            alert(count);                           
        }                   
    }       
}

Upvotes: 1

Related Questions