实际上,我正在为我的大学项目使用快速API,并希望根据给定的出发日期和返回日期显示机票。响应是这样的响应结果图像我只想显示purchaseLinks数组信息,基本上我想映射航班和purchaseLinks数组每个purchaseLinks有17个键我通常会把所有信息包装在一个引导卡中,以获得良好的UI
我知道这是错误的,但我只是试着做这个
fetch(mainUrl, options)
.then(response => response.json())
.then(response => {
const res = response.data.flights.purchaseLinks.map(e => e.commerceName);
console.log(res);
//console.log(response.data.flights[0].purchaseLinks[0].commerceName)
})
我尝试控制台日志只是第一个,这是非常简单的,但就像我想做的所有信息在给定的结果json。我真的被困在这里了有什么办法可以做到吗?如果是,请指导你的同事谢谢你:)
const res = response.data.flights.map(f => f.purchaseLinks.map(e => e.commerceName));
如果你需要2d数组和
const res = response.data.flights.flatMap(f => f.purchaseLinks).map(e => e.commerceName));
1 d
如果purchaseLinks
数组将始终包含单个对象。在这种情况下,您可以简单地对flights
数组应用.map方法,然后使用zero
索引访问purchaseLinks
数组对象。
Live Demo:
const flights = [{
segemtns: [],
purchaseLinks: [{
commerceName: 'Alpha'
}]
}, {
segemtns: [],
purchaseLinks: [{
commerceName: 'Beta'
}]
}, {
segemtns: [],
purchaseLinks: [{
commerceName: 'Gamma'
}]
}, {
segemtns: [],
purchaseLinks: [{
commerceName: 'Abc'
}]
}, {
segemtns: [],
purchaseLinks: [{
commerceName: 'Xyz'
}]
}];
const link = flights.map(obj => obj.purchaseLinks[0].commerceName);
console.log(link);
如果purchaseLinks包含多个对象,那么您可以使用两个map
来获得所有commerceName
。
Live Demo:
const flights = [{
segemtns: [],
purchaseLinks: [{
commerceName: 'Alpha'
}, {
commerceName: 'A1'
}]
}, {
segemtns: [],
purchaseLinks: [{
commerceName: 'Beta'
}, {
commerceName: 'B1'
}]
}, {
segemtns: [],
purchaseLinks: [{
commerceName: 'Gamma'
}, {
commerceName: 'G1'
}]
}, {
segemtns: [],
purchaseLinks: [{
commerceName: 'Abc'
}]
}, {
segemtns: [],
purchaseLinks: [{
commerceName: 'Xyz'
}]
}];
const link = flights.map(obj => {
return obj.purchaseLinks.map(linkObj => linkObj.commerceName)
});
console.log(link.flat());