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

JS如何根据输入匹配获取对象值?嵌套数组场景处理求助

航班数据筛选解决方案

需求回顾

需要筛选出**出发地为马尼拉(Manila (MNL))、目的地为曼谷(Bangkok (DMK))**的所有航班,包括:

  • 直飞航班
  • 所有嵌套在connect数组中的中转航班

修改后的实现代码

首先定义筛选条件:

const from = 'Manila (MNL)';
const to = 'Bangkok (DMK)';

1. 筛选直飞航班

直接匹配出发地和目的地的航班:

// 筛选符合条件的直飞航班
const directFlights = flightsData.filter(flight => 
  flight.start === from && flight.destination === to
);

2. 提取中转航班

遍历所有航班,过滤出带有connect数组且出发地匹配的航班,再从中提取目的地符合要求的中转航班:

// 提取所有符合条件的中转航班
const connectingFlights = flightsData.flatMap(flight => {
  // 仅处理出发地匹配且包含connect数组的航班
  if (flight.start === from && Array.isArray(flight.connect)) {
    return flight.connect.filter(connectFlight => connectFlight.destination === to);
  }
  // 不符合条件时返回空数组,不影响最终结果
  return [];
});

3. 合并所有符合条件的航班

把直飞和中转航班数组合并,得到最终结果:

const allQualifiedFlights = [...directFlights, ...connectingFlights];

备选实现方式

如果不熟悉flatMap,也可以用forEach遍历收集中转航班:

const connectingFlights = [];
flightsData.forEach(flight => {
  if (flight.start === from && Array.isArray(flight.connect)) {
    const matchedConnectFlights = flight.connect.filter(f => f.destination === to);
    connectingFlights.push(...matchedConnectFlights);
  }
});

内容的提问来源于stack exchange,提问作者Diego Sanchez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 15:55:08