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!

2
  • See stackoverflow.com/questions/5223/… Commented Jun 8, 2011 at 18:33
  • yep i can delete, maybe the other question should be retitled, its a bit deceiving since js doesn't even have associative arrays Commented Jun 9, 2011 at 0:56

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Did you mean to pass Object.keys the count function?
@Eric, nope, I sure didn't. Cheers.
Thanks, maybe it's not cross-browser yet, but works well in node.js server side ;)
7

.length only works on arrays, not objects.

var count = 0;
for(var key in json)
    if(json.hasOwnProperty(key))
        count++;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.