4 回答

TA貢獻1788條經驗 獲得超4個贊
這是你需要的嗎?(我正在考慮您的響應存儲在一個名為data)
data.origin_destinations.forEach(destination => {
destination.segments.forEach(segment => {
console.log(segment);
});
});
兩者都是數據中的數組。origin_destinationssegments
ES5 語法中的相同解決方案:
data.origin_destinations.forEach(function(destination) {
destination.segments.forEach(function(segment) {
console.log(segment);
});
});
請參閱下面的運行代碼段:
var data = {
"origin_destinations": [
{
"ref_number": "0",
"direction_id": "0",
"elapsed_time": "2435",
"segments": [
{
"departure": {
"date": "2020-05-20",
"time": "20:45:00",
"airport": {
"code": "LOS",
"name": "Lagos-Murtala Muhammed Intl, Nigeria",
"city_code": "",
"city_name": "Lagos",
"country_code": "NG",
"country_name": "Nigeria",
"terminal": "I"
}
},
}
]
}
]
};
data.origin_destinations.forEach(function(destination) {
destination.segments.forEach(function(segment) {
console.log(segment);
});
});

TA貢獻1900條經驗 獲得超5個贊
如果您更喜歡使用功能較少的方法,也可以編寫類似于以下代碼的代碼,您可以在瀏覽器上運行它。
function processData(data) {
for (const originDestination of data.origin_destinations) {
const {
ref_number,
direction_id,
elapsed_time,
segments
} = originDestination
console.log({
ref_number,
direction_id,
elapsed_time
})
for (const segment of segments) {
const {
departure
} = segment
console.log(departure)
}
}
}
const data = {
"origin_destinations": [{
"ref_number": "0",
"direction_id": "0",
"elapsed_time": "2435",
"segments": [{
"departure": {
"date": "2020-05-20",
"time": "20:45:00",
"airport": {
"code": "LOS",
"name": "Lagos-Murtala Muhammed Intl, Nigeria",
"city_code": "",
"city_name": "Lagos",
"country_code": "NG",
"country_name": "Nigeria",
"terminal": "I"
}
}
}]
}]
}
processData(data)

TA貢獻1906條經驗 獲得超10個贊
這是我的響應數據的樣子
"data": {
"itineraries": [{
"origin_destinations":[{
"segments":[
"departure":{
"airport": {
"code": "LOS",
"name": "Lagos-Murtala Muhammed Intl, Nigeria",
"city_code": "",
"city_name": "Lagos",
"country_code": "NG",
"country_name": "Nigeria",
"terminal": "I"
}
}
]
}]
}]
}
我用它來解構返回數據
const {
data: {
body: {
data: {
itineraries: [...origin_destinations]
}
}
}
} = resp;

TA貢獻1877條經驗 獲得超6個贊
我的一個朋友幫我解決了這個問題。下面是他的代碼片段。
var data = [
{
"origin_destinations":[
{
"ref_number":"0",
"direction_id":"0",
"elapsed_time":"2435",
"segments":[
{
"departure":{
"date":"2020-05-20",
"time":"20:45:00",
"airport":{
"code":"LOS",
"name":"Lagos-Murtala Muhammed Intl, Nigeria",
"city_code":"",
"city_name":"Lagos",
"country_code":"NG",
"country_name":"Nigeria",
"terminal":"I"
}
},
"arrival":{
"date":"2020-05-20",
"time":"20:45:00",
"airport":{
"code":"LOS",
"name":"Lagos-Murtala Muhammed Intl, Nigeria",
"city_code":"",
"city_name":"Lagos",
"country_code":"NG",
"country_name":"Nigeria",
"terminal":"I"
}
}
}
]
}
]
}
];
data.forEach(function(row) {
row.origin_destinations.forEach(function(destination) {
destination.segments.forEach(function(segments) {
console.log(segments.departure.airport.name);
});
});
});
添加回答
舉報