javascript - JSON - 查找对象的长度

标签 javascript json

嗨,

我有一个 JSON 解析的返回对象集。

{
  "word":[
      "offered",
      "postings"
  ],

  "annotation":[
      ["offered highlighted","this is also given as annotation","This annotation has been added here currently","offering new annotation points","\"offered\" is in the sense of languages"],
      ["my postings","this is new annotation for postings.","my postings","this is posting annotation.... Working for the feature of the annotation."]
  ],

  "user":[
  ["","","vinoth","Anonymous","Vinoth"],
  ["Anonymous","vinoth","Anonymous","Arputharaj"]
  ],

  "id":[
  ["58","60","61","63","68"],
  ["32","57","59","62"]
  ],

  "comment":
  {
    "id58":["first comment","This is a old comment for this annotation","Next level of commenting.","Fourth comment to this annotation","testing"],
    "id61":["this is an old annotation.\r\nMy comment is very bad about this.","Second comment to this annotation"],
    "id57":["I want to add one more comment to this"]
    },

    "commentUser":{
      "id58":["vinoth","Anonymous","Vinothkumar","Vinothkumar","vinoth"],
      "id61":["Anonymous","Commentor"],
      "id57":["vinoth"]
      }
  }

我想知道每个对象和数组的长度。

我使用.length来获取annotation[0].length的长度。我得到了预期的结果,即:5。“user”和“id”也是如此。

但我没有得到“word”、“id58”、“id61”等的长度... 我还想知道 commentcommentUser 的长度。

请帮助我。

最佳答案

要计算对象拥有的属性数量,您需要循环遍历属性,但请记住使用 hasOwnProperty 函数:

var count = 0;
for (var p in obj) {
    if (obj.hasOwnProperty(p)) {
        count++;
    }
}

如果您忘记这样做,您将循环访问继承的属性。如果您(或某个库)已为 Object 的原型(prototype)分配了一个函数,那么所有对象似乎都具有该属性,因此看起来有一个项目比它们本质上“更长”。

为了避免记住这一点,请考虑使用 jQuery 的 each 来代替:

var count = 0;
$.each(obj, function(k, v) { count++; });

更新使用当前浏览器:

Object.keys(someObj).length

关于javascript - JSON - 查找对象的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3385820/

相关文章:

javascript - Electron javascript不同文件中的单独类

javascript - 有没有办法将 CSS 转换应用于在 mousemove 上进行 CSS 转换的元素内的元素?

javascript - 使用列表中子元素值的 attr 更改 div 类的 css

node.js - SQLite3 Node.js JSON

c# - 在 C# 中从复杂的 JSON 结构中提取数据

c# - 在 RestSharp 中获取 REST 请求的原始 JSON 数据

java - 使用用索引项表示的集合生成 JSON

javascript - 滚动问题 - 未定义的属性 'top'

javascript - 使用Vim的ALE插件时有没有办法指定默认的eslint配置文件?

jquery - JStree 设置链接 href 和重定向