Javascript 获取 Json 对象上的项目总数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13782698/
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-24 12:53:21  来源:igfitidea点击:

Get total number of items on Json object?

javascriptjson

提问by lisovaccaro

Possible Duplicate:
Length of Javascript Object (ie. Associative Array)

可能的重复:
Javascript 对象的长度(即关联数组)

I have an object similar to this one:

我有一个类似于这个的对象:

var jsonArray = {
  '-1': {
    '-1': 'b',
    '2': 'a',
    '10': 'c'
  },
  '2': {
    '-1': 'a',
    '2': 'b',
    '10': 'a'
  },
  '5': {
    '-1': 'a',
    '2': 'a',
    '10': 'b'
  }
};

I'm trying to get it's length, the problem is that jsonArray.lengthreturns 5 instead of 3 (which is the total items it has). The array is relatively long (has 1000x2000 items) and this must be done a lot of times every second. How can I get the number of items more efficiently?

我正在尝试获取它的长度,问题是jsonArray.length返回 5 而不是 3(这是它拥有的总项目数)。该数组相对较长(有 1000x2000 个项目),并且每秒必须执行很多次。如何更有效地获取项目数量?

回答by NT3RP

In addition to kieran's answer, apparently, modern browsers have an Object.keysfunction. In this case, you could do this:

除了基兰的回答,显然,现代浏览器还有一个Object.keys功能。在这种情况下,您可以这样做:

Object.keys(jsonArray).length;

More details in this answer on How to list the properties of a javascript object

此答案中有关如何列出 javascript 对象的属性的更多详细信息

回答by Alexander

That's an Object and you want to count the properties of it.

那是一个对象,你想计算它的属性。

Object.keys(jsonArray).length

References:

参考:

回答by kieran

Is that your actual code? A javascript object (which is what you've given us) does not have a length property, so in this case exampleArray.lengthreturns undefined rather than 5.

那是你的实际代码吗?javascript 对象(这是您提供给我们的)没有 length 属性,因此在这种情况下exampleArray.length返回 undefined 而不是 5。

This stackoverflowexplains the length differences between an object and an array, and this stackoverflowshows how to get the 'size' of an object.

此 stackoverflow解释了对象和数组之间的长度差异,此 stackoverflow显示了如何获取对象的“大小”。