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

我有一个类似于这个的物体:

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.length returns 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?

推荐答案

显然,除了基兰的答案之外,现代浏览器还有Object.keys的功能.在这种情况下,您可以执行以下操作:

Object.keys(jsonArray).length;

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

Json相关问答推荐

如何在对象投影(*)上应用滤镜投影([?port==`eth1`])?

无法从JSON解析ZonedDateTime,但可以使用格式化程序很好地解析

在Vega中如何通过滑块改变条形图的宽度

Oracle plsql:如何将json文件加载到嵌套表中

如何将具有相同 struct 的多个JSON文件中的对象数组合并成一个数组?

JOLT转换并向输出添加新数组

Jolt 规范将父对象中的所有键应用于数组中的所有对象

将来自 Golang 的 JSON API 调用响应输出到 nextjs 前端

Vue 3如何将参数作为json发送到axios get

jq搜索特定字符串并输出对应的父值

下一个 Js 部署在 getStaticPath 函数上失败:在 JSON.parse 的位置 0 的 JSON 中出现意外的令牌 < 但在本地运行

hook到 Decodable.init() 以获得未指定的键?

如何在 jQuery 中循环遍历 JSON 数组?

Flask 请求和 application/json 内容类型

使用 @ResponseBody 自定义 HttpMessageConverter 来做 Json 事情

将字符串映射到json对象的多种类型?

如何在 Perl 中将简单的哈希转换为 json?

字符串格式 JSON 字符串给出 KeyError

按键值过滤 JSON

TypeError:使用Python解析JSON时字符串索引必须是整数?