You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在嵌套数组中使用map?Rapid API航班数据展示求助

问题:遍历嵌套航班数据并渲染Bootstrap卡片

我正在为大学项目使用Rapid API,想要根据出发日期和返程日期展示航班机票信息。API返回的是嵌套结构数据,其中flights数组的每个元素都包含purchaseLinks数组(每个元素有17个字段)。我希望遍历这两个数组,把所有信息用Bootstrap卡片展示,但尝试的代码只能打印第一个元素的信息,无法遍历所有数据:

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)
  })

解决方案

你的核心问题是没有正确遍历嵌套数组:response.data.flights本身是数组,不能直接访问flights.purchaseLinks,必须先遍历每个航班,再遍历该航班下的purchaseLinks。以下是完整的实现方案:

1. 正确遍历嵌套数组

使用flatMap扁平化所有purchaseLinks数据,或者用嵌套forEach处理每一层数据:

fetch(mainUrl, options)
  .then(response => response.json())
  .then(data => {
    // 扁平化所有航班的purchaseLinks数据
    const allPurchaseLinks = data.data.flights.flatMap(flight => flight.purchaseLinks);
    console.log(allPurchaseLinks); // 现在能拿到所有purchaseLinks数据
    
    // 调用渲染函数生成Bootstrap卡片
    renderFlightCards(allPurchaseLinks);
  })
  .catch(err => console.error('请求失败:', err));

2. 渲染Bootstrap卡片

先在页面中准备一个容器用于放置卡片:

<div id="flight-cards-container" class="container mt-4"></div>

然后编写渲染函数,将数据转换成Bootstrap卡片HTML并插入容器:

function renderFlightCards(links) {
  const container = document.getElementById('flight-cards-container');
  container.innerHTML = ''; // 清空容器旧内容

  links.forEach(link => {
    // 根据API返回的字段自定义卡片内容,注意做空值判断避免报错
    const cardHtml = `
      <div class="col-lg-4 col-md-6 mb-4">
        <div class="card h-100">
          <div class="card-body">
            <h5 class="card-title">${link.commerceName || '未知商家'}</h5>
            <p class="card-text">
              <strong>价格:</strong>${link.price?.amount || '暂无'} ${link.price?.currency || ''}<br>
              <strong>出发时间:</strong>${link.departureDateTime || '未提供'}<br>
              <strong>到达时间:</strong>${link.arrivalDateTime || '未提供'}
            </p>
          </div>
          <div class="card-footer">
            <a href="${link.url}" class="btn btn-primary btn-sm" target="_blank">预订链接</a>
          </div>
        </div>
      </div>
    `;
    container.insertAdjacentHTML('beforeend', cardHtml);
  });
}

关键注意事项

  • 确保页面已引入Bootstrap的CSS文件,否则卡片样式不生效
  • 对API返回的字段做空值判断(比如link.price?.amount),避免因字段缺失导致页面报错
  • 如果flights数组可能为空,需先判断data.data.flights?.length > 0再执行后续逻辑

内容的提问来源于stack exchange,提问作者Dhruv Dornal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 21:05:13