techlead
techlead

Reputation: 779

Finding the number of object properties

I have the following 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;
            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?

Upvotes: 0

Views: 476

Answers (2)

Ben L
Ben L

Reputation: 2571

The problem is that "code" is an object, not an array. You can't get the length of an object in javascript. You'll have to loop through the object with a "for in" loop like below: (warning: untested).

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

Upvotes: 2

roselan
roselan

Reputation: 3775

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)

Upvotes: 0

Related Questions