开发者

Count Key/Values in JSON [duplicate]

This question already has answers here: Closed 11 years ago.

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 r开发者_运维问答ead 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 only works on arrays, not objects.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜