javascript 我如何在一个数组中使用map,它有另一个数组?

b1zrtrql  于 2023-04-04  发布在  Java
关注(0)|答案(2)|浏览(102)

实际上,我正在为我的大学项目使用Rapid API,并希望根据给定的出发日期和返回日期显示航班机票。响应类似于the response results image我只是想显示purchaseLinks数组信息,基本上我想Map航班和purchaseLinks数组every purchaseLinks has got 17 keys我主要将所有信息 Package 在引导卡中以获得良好的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.我真的被困在这里有什么可能的方法来做到这一点?如果是的,请指导你的同伴初级谢谢:)

px9o7tmv

px9o7tmv1#

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天

6l7fqoea

6l7fqoea2#

如果purchaseLinks数组总是包含一个对象。在这种情况下,您可以简单地对flights数组应用.map方法,然后使用zero索引访问purchaseLinks数组对象。
现场演示**:**

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
现场演示**:**

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());

相关问题