0

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?

0

2 Answers 2

2

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
        }
}
Sign up to request clarification or add additional context in comments.

Comments

0
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)

1 Comment

@SK11 not data.rowItem.code, rowItem.code (how could data have the object rowItem)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.