JSON - 查找对象的长度

2024-04-03

HI,

我有一个 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。“用户”和“id”也是如此。

但我没有得到“word”、“id58”、“id61”等的长度...... 我也想知道长度comment & commentUser.

请帮助我。


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

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

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

为了避免记住这一点,请考虑使用 jQueryeach反而:

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

UPDATE使用当前浏览器:

Object.keys(someObj).length
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JSON - 查找对象的长度 的相关文章

随机推荐