24

Possible Duplicate:
Length of Javascript Associative Array

I have a JSON that looks like this:

Object:
   www.website1.com : "dogs"
   www.website2.com : "cats"
   >__proto__ : Object

This prints when I do this:

console.log(obj);

I am trying to get the count of the items inside this JSON, obj.length returns "undefined" and obj[0].length returns

Uncaught TypeError: Cannot read property 'length' of undefined

I would expect a length to return "2" in this case. How can I find the count?

Thanks!

Community
  • 1
  • 1
Doug Molineux
  • 12,283
  • 25
  • 92
  • 144

2 Answers2

32

You have to count them yourself:

function count(obj) {
   var count=0;
   for(var prop in obj) {
      if (obj.hasOwnProperty(prop)) {
         ++count;
      }
   }
   return count;
}

Although now that I saw the first comment on the question, there is a much nicer answer on that page. One-liner, probably just as fast if not faster:

function count(obj) { return Object.keys(obj).length; }

Be aware though, support for Object.keys() doesn't seem cross-browser just yet.

davin
  • 44,863
  • 9
  • 78
  • 78
7

.length only works on arrays, not objects.

var count = 0;
for(var key in json)
    if(json.hasOwnProperty(key))
        count++;
Eric
  • 95,302
  • 53
  • 242
  • 374