2010-08-02 72 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