How can I iterate over an array that is accesed by a key in a json Object
本问题已经有最佳答案,请猛点这里访问。
这是我的字符串化JSON对象:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | { "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循环没有迭代,因为我忘记在iterable中的对象变量之前放置一个"var"。
简单的for循环应该足够:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | 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 2 3 | $.each(json.bookingsList, function(index, prop){ console.log(prop); }); |