nkcmr nkcmr - 4 months ago 13x
JSON Question

get size of json object

i have a json object that gets returned by an AJAX request and I am having some trouble with the

because it keeps returning
. Just wondering if I'm using it right:


They both return
even though they are valid objects.


Sample of the JSON object returned:



Your problem is that your phones object doesn't have a length property (unless you define it somewhere in the JSON that you return) as objects aren't the same as arrays, even when used as associative arrays. If the phones object was an array it would have a length. You have two options (maybe more).

1) Change your JSON structure (assuming this is possible) so that 'phones' becomes


(note there is no word-numbered identifier for each phone as they are returned in a 0-indexed array). In this response phones.length will be valid.

2) Iterate through the objects contained within your phones object and count them as you go, e.g.

var key, count = 0;
for(key in data.phones) {
  if(data.phones.hasOwnProperty(key)) {

If you're only targeting new browsers option 2 could look like this