代码之家  ›  专栏  ›  技术社区  ›  Vinothkumar Arputharaj

JSON-查找对象的长度

  •  0
  • Vinothkumar Arputharaj  · 技术社区  · 15 年前

    你好,

    我有一个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”。

    comment & commentUser .

    请帮帮我。

    2 回复  |  直到 15 年前
        1
  •  5
  •   AKX Bryan Oakley    15 年前

    word 在你的例子中(我们称之为 obj )是数组,所以 obj.word.length 应该是2。

    comment commentUser 是一个本身没有长度的对象,因此您需要自己计算它们:

    var length=0;
    for(var dummy in obj.comment) length++;
    
        2
  •  7
  •   Daniel Earwicker    13 年前

    hasOwnProperty 功能:

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

    Object ,则所有对象似乎都具有该属性,因此看起来比它们本质上更长。

    为了避免记住这一点,可以考虑使用jQuery的 each

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

    更新 对于当前浏览器:

    Object.keys(someObj).length