2010-08-02 74 views
0

嗨,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.对于“用户”&“id”也是如此。

但我没有收到“字”,“id58”,“id61”等的长度...... 此外,我想了解的comment & commentUser长度。

请帮我这个。

回答

5

在你的例子的关键word(让我们称之为obj)的值是一个数组,所以obj.word.length应该为2

commentcommentUser值是一个对象,该对象不具有长度本身,所以你需要自己算来:

var length=0; 
for(var dummy in obj.comment) length++; 
+0

谢谢你这个答案。这适用于“评论”和“评论使用者”。但是“myObj.word.length”返回“undefined” (myObj是我的对象)。 – 2010-08-02 08:15:36

+0

@Vinothkumar Arputharaj - 假设'myObj'具有在你的示例代码中给出的定义,那么'myObj.word'是一个长度为2的数组。如果你发现'myObj.word.length'是'undefined',那么一部分你描述的情况是错误的。为什么不在浏览器中设置断点并检查数据?您可以在Firefox中使用Firebug或使用IE 8和Chrome的内置调试器来执行此操作。 – 2010-08-02 10:07:28

+0

但是,我可以通过使用for循环来计算** myObj.word.length **的长度。 – 2010-08-02 10:24:24

7

要计算属性的对象有多少,你需要通过性循环,但记得要使用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++; }); 

UPDATE利用当前的浏览器:

Object.keys(someObj).length