2012-06-07 69 views
0

我正嘗試使用for..in循環來訪問'Event'中的描述鍵/值,但目前我還不完全確定如何實現這一點。首先,我使用for..in並將其記錄下來,這將返回響應中的所有頂級條目,現在我要如何深入分析並選擇Event.description?我首先認爲它是數據[prop] .Event.description,但事實並非如此。我應該使用正常的循環,然後在這裏for..in?從我的JSON響應中訪問特定的一組值?

這裏是我當前的代碼:

$(document).ready(function() { 

    var data = { 
     "status": "ok", 
     "code": "200", 
     "message": "event details", 
     "data": [{ 
      "Event": { 
       "id": "1", 
       "name": "Sample Event Number 1", 
       "description": "Sample Event Number 4 Description ....", 
       "event_date": "2012-05-31 00:00:00", 
       "Band": [{ 
        "id": "1", 
        "name": "Support #1", 
        "BandsEvent": { 
         "id": "7", 
         "band_id": "2", 
         "event_id": "8", 
         "created": "2012-05-23 15:53:56", 
         "modified": "2012-05-23 15:53:56" 
        }}, 
       { 
        "id": "2", 
        "name": "Support #2", 
        "BandsEvent": { 
         "id": "8", 
         "band_id": "1", 
         "event_id": "8", 
         "created": "2012-05-23 15:53:57", 
         "modified": "2012-05-23 15:53:57" 
        }}] 
      }}, 
     { 
      "Event": { 
       "id": "2", 
       "name": "Sample Event Number 2", 
       "description": "Sample Event Number 4 Description ....", 
       "event_date": "2012-05-31 00:00:00", 
       "Band": [{ 
        "id": "2", 
        "name": "Another Crazy Band", 
        "BandsEvent": { 
         "id": "3", 
         "band_id": "2", 
         "event_id": "8", 
         "created": "2012-05-23 15:53:56", 
         "modified": "2012-05-23 15:53:56" 
        }}, 
       { 
        "id": "4", 
        "name": "The Band", 
        "BandsEvent": { 
         "id": "8", 
         "band_id": "1", 
         "event_id": "8", 
         "created": "2012-05-23 15:53:57", 
         "modified": "2012-05-23 15:53:57" 
        }}] 

      }}] 
    } 


    var prop; 

    for (prop in data) { 
     console.log(data[prop]); 
     // data.Event.description 
    } 

});​ 

回答

1

這應該做你想要什麼:

for (var i = 0; i < data.data.length; i++) { 
    console.log(data.data[i].Event.description);   
} 

我要補充一點,你的代碼不起作用的原因是,「prop」變量首先是「status」,然後是「code」,然後是「message」,然後是「data」。狀態/代碼/消息沒有「Event」屬性,因此如果您嘗試訪問data[prop].Event,那麼您的代碼將返回undefined。在這裏我們特意挑選它們。而且由於data.data是一個數組,所以沒有理由使用循環,而只是一個普通的for循環。

同樣的,如果你想打印出來的描述和樂隊,你可以做到以下幾點:

for (var i = 0; i < data.data.length; i++) { 
    console.log(data.data[i].Event.description + " has the following bands:"); 
    for (var j = 0; j < data.data[i].Event.Band.length; j++) { 
     console.log(data.data[i].Event.Band[j].name); 
    }  
} 
+0

我會建議在存儲的陣列和循環:'爲 (VAR事件= data.data,i = 0,n = events.length; i mplungjan