Javascript 计算 JSON 中的键/值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6283466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:06:11  来源:igfitidea点击:

Count Key/Values in JSON

javascriptjson

提问by Doug Molineux

Possible Duplicate:
Length of Javascript Associative Array

可能的重复:
Javascript 关联数组的长度

I have a JSON that looks like this:

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

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

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

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?

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

Thanks!

谢谢!

回答by davin

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.

但请注意,对 的支持Object.keys()似乎还不是跨浏览器。

回答by Eric

.lengthonly works on arrays, not objects.

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

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