Javascript : array.length returns undefined

I have a set of data that is being passed on by the PHP’s json_encode function. I’m using the jQuery getJSON function to decode it:

$.getJSON("url", function (data) {
    console.log(data);
});

The output looks like this in the console:

Object {1: Object, 2: Object, 3: Object, 4: Object, 5: Object, 6: Object, 7: Object, 8: Object, 9: Object, 10: Object}

I can access each array by using data[1], data[2] etc, but to make it easier I thought of looping thought it so I can access all at once:

$.getJSON("url", function (data) {
    for (var i = 0, len = data.length; i < len; i++) {
        //do something
    }
});

However I can’t get this to work because the data.length returns the value undefined. What is wrong and how can I fix it?

Leave a Comment