请有人帮助或指导我有关如何解决此问题的写资源。在我的节点应用程序中,我正在发出API POST请求以访问公共航班结果。我的回复数据如下所示:
{
"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"
}
},
}
]
}
]
}
按现状,我发现很难访问段Array中的数据。
答案 0 :(得分:1)
这是您需要的吗? (我考虑您的回复存储在名为data
的变量中)
data.origin_destinations.forEach(destination => {
destination.segments.forEach(segment => {
console.log(segment);
});
});
origin_destinations
和segments
都是数据中的数组。
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);
});
});
答案 1 :(得分:0)
这是我的响应数据的样子
"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;
答案 2 :(得分:0)
如果您喜欢使用功能较少的方法,还可以编写类似以下代码的代码,然后就可以在浏览器上直接运行它。
1 2 3 4 5 6 7 8 9 10
答案 3 :(得分:0)
我的一个朋友帮助我解决了这个问题。...下面是他的代码段。
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);
});
});
});