用JSON计算键/值 [英] Count Key/Values in JSON

查看:52
本文介绍了用JSON计算键/值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Javascript关联数组的长度

我有一个JSON,看起来像这样:

I have a JSON that looks like this:

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

当我这样做时打印:

console.log(obj);

我正在尝试获取此JSON中的项目计数,obj.length返回undefined和obj [0] .length返回

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


未捕获TypeError:无法读取未定义属性'length'

Uncaught TypeError: Cannot read property 'length' of undefined

在这种情况下,我希望长度返回2。我怎样才能找到计数?

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

谢谢!

推荐答案

你必须自己计算:

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; }

请注意,支持 Object.keys()目前还没有跨浏览器。

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

这篇关于用JSON计算键/值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆