如何迭代json对象中的键所接受的数组

时间:2016-01-26 14:22:34

标签: jquery 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中的对象?我将在桌子上放置一些属性。

编辑:事实证明,对于in循环,我正在使用isn&#t; t迭代,因为我忘了放置" var"在迭代中的对象变量之前。

2 个答案:

答案 0 :(得分: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
}

答案 1 :(得分:0)

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