2011-11-12 54 views
0

我有以下JSON結構查找對象的屬性數

{ 
     "codes":[ 
      { 
        "id":"1",   
        "code":{     
         "fname":"S", 
         "lname":"K" 

       } 
      }, 
      { 
        "id":"2",    
        "code":{     
         "fname":"M", 
         "lname":"D"     
       } 
      } 
    ] 
    } 

欲通過每個碼循環和每個碼

 success: function (data) {    
      var x; 
      for (x = 0; x < data.codes.length; x++){    
       alert(data.codes[x].id); // alerts the ID of each 'codes' 
       alert(data.codes[x].code.length) // returns undefined 
      } 
    } 

內警報屬性的數量我該怎麼做呢?

回答

2

問題是「代碼」是一個對象,而不是一個數組。您無法在JavaScript中獲取對象的長度。你必須用下面的「for in」循環遍歷對象:(warning:未經測試)。

success: function (data) {    
     var x, codeProp, propCount; 
     for (x = 0; x < data.codes.length; x++){    
      alert(data.codes[x].id); // alerts the ID of each 'codes' 
      propCount = 0; 
      for (codeProp in data.codes[x]) { 
       if (data.codes[x].hasOwnProperty(codeProp) { 
        propCount += 1; 
       } 
      } 

      alert(propCount) // should return number of properties in code 
     } 
} 
0
if (data && rowItem.code) { 

,或者,如果你喜歡直接做:

if (data && data.codes[x].code) { 

注,在「數據」的檢查是無用的,因爲你的代碼迴路「數據」的元素(即,如果數據沒有按」 t存在,data.codes.length只能爲0,for循環永遠不會啓動)

+0

@ SK11不'data.rowItem.code','rowItem.code'(怎麼可能有數據的對象rowItem) – noob