Count Key/Values in JSON

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!


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.


.length仅适用于数组,不适用于对象。

var count = 0;
for(var key in json)
    if(json.hasOwnProperty(key))
        count++;
链接地址: http://www.djcxy.com/p/27256.html

上一篇: 用Javascript检查多维数组的长度

下一篇: 在JSON中计数键/值