2016-01-26 72 views
-1

accesed數組這是我的字符串化JSON對象:我如何可以遍歷由一個鍵一個JSON對象

{ 
    "bookingsList": [{ 
     "bookingID": 5, 
     "destination": "BSO", 
     "flightDate": "2015-12-07T00:00:00", 
     "flightScheduleId": 113, 
     "origin": "MNL", 
     "passengerList": [{ 
      "availedInsurance": true, 
      "availedMeal": false, 
      "birthDate": null, 
      "carryOnBaggage": 5.1, 
      "checkInBaggage": 4.5, 
      "columnId": 1, 
      "firstname": "Peter", 
      "gender": "M", 
      "lastname": "North", 
      "middlename": "West", 
      "nationality": null, 
      "rowId": "A" 
     }] 
    }, { 
     "bookingID": 6, 
     "destination": "BSO", 
     "flightDate": "2015-12-07T00:00:00", 
     "flightScheduleId": 113, 
     "origin": "MNL", 
     "passengerList": [{ 
      "availedInsurance": false, 
      "availedMeal": false, 
      "birthDate": null, 
      "carryOnBaggage": 4.2, 
      "checkInBaggage": 3.4, 
      "columnId": 2, 
      "firstname": "Mark Justin", 
      "gender": "M", 
      "lastname": "Jalandoni", 
      "middlename": "Manzano", 
      "nationality": null, 
      "rowId": "A" 
     }] 
    }] 
} 

那麼,如何遍歷在bookingsList的對象?我將把一些屬性放在桌子上。

編輯:原來我在循環中使用的是沒有迭代,因爲我忘記了在迭代中的對象變量之前放置一個「var」。

+0

'bookingsList'僅僅是一個陣列,使得任何循環結構都可以,例如一個普通的舊'for'迴路。 –

+0

你知道循環概念? – Sandeep

回答

0
$.each(json.bookingsList, function(index, prop){ 
    console.log(prop); 
}); 
+1

僅有代碼的答案在幫助OP瞭解正在發生的事情方面並不真正有用。也許給你一個簡短的解釋你的答案。 – wpercy

1

一個簡單的for循環應該足夠了:

var jsonObj = { 
    "bookingsList": [{ 
     "bookingID": 5, 
     "destination": "BSO", 
     "flightDate": "2015-12-07T00:00:00", 
     "flightScheduleId": 113, 
     "origin": "MNL", 
     "passengerList": [{ 
      "availedInsurance": true, 
      "availedMeal": false, 
      "birthDate": null, 
      "carryOnBaggage": 5.1, 
      "checkInBaggage": 4.5, 
      "columnId": 1, 
      "firstname": "Peter", 
      "gender": "M", 
      "lastname": "North", 
      "middlename": "West", 
      "nationality": null, 
      "rowId": "A" 
     }] 
    }, { 
     "bookingID": 6, 
     "destination": "BSO", 
     "flightDate": "2015-12-07T00:00:00", 
     "flightScheduleId": 113, 
     "origin": "MNL", 
     "passengerList": [{ 
      "availedInsurance": false, 
      "availedMeal": false, 
      "birthDate": null, 
      "carryOnBaggage": 4.2, 
      "checkInBaggage": 3.4, 
      "columnId": 2, 
      "firstname": "Mark Justin", 
      "gender": "M", 
      "lastname": "Jalandoni", 
      "middlename": "Manzano", 
      "nationality": null, 
      "rowId": "A" 
     }] 
    }] 
} 

// For easy reference 
var bookingsList = jsonObj.bookingsList; 

for (i = 0; i < bookingsList.length; i++) { 
    var booking = bookingsList[i]; // Grab booking data 
    console.log(booking.bookingID); // Log booking data 
}