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

如何遍历嵌套键值对并基于数组值过滤实现搜索功能

实现嵌套对象的搜索匹配功能

没问题,我来帮你搞定这个搜索需求。你的场景是要遍历嵌套的trips对象,检查其中所有值是否匹配FilteredSelectedOptions数组里的任意项,筛选出符合条件的行程。因为结构是嵌套的(有对象、数组多层嵌套),我们可以用递归遍历的方式来处理所有层级的值,下面是具体的实现方案:

步骤1:定义核心检查函数

首先写一个递归函数,用来遍历任意嵌套结构(对象或数组),判断是否存在值匹配目标搜索数组中的任意元素。注意要处理类型转换,比如数字转字符串,避免因为类型不匹配导致漏判:

const FilteredSelectedOptions = ["20180211","Trax","Vienna","AN01020"];

// 递归检查嵌套结构中是否有值匹配搜索数组
function matchesSearchTerm(item) {
  // 如果当前项是数组,遍历每个元素检查
  if (Array.isArray(item)) {
    return item.some(subItem => matchesSearchTerm(subItem));
  }
  // 如果当前项是对象,遍历每个值检查
  if (typeof item === 'object' && item !== null) {
    return Object.values(item).some(value => matchesSearchTerm(value));
  }
  // 基础类型,转成字符串后判断是否在搜索数组中
  const valueStr = String(item).trim();
  return FilteredSelectedOptions.includes(valueStr);
}

步骤2:遍历trips对象筛选结果

接下来遍历trips的所有日期分组,对每个行程应用上面的检查函数,收集符合条件的行程:

const trips = {
  "20180201": [
    {
      "journeyId": 1001,
      "Number": "001",
      "DriverName": "Alex",
      "Transporter": {
        "id": "T1",
        "number": "AN01001",
        "Company": "Tranzient"
      },
      "place": [
        { "id": 1, "name": "Vienna" },
        { "id": 2, "name": "Berlin" }
      ]
    },
    {
      "journeyId": 1002,
      "Number": "002",
      "DriverName": "Mike",
      "Transporter": {
        "id": "T2",
        "number": "AN01020",
        "Company": "Trax"
      },
      "place": [
        { "id": 3, "name": "Paris" }
      ]
    }
  ],
  "20180211": [
    {
      "journeyId": 1003,
      "Number": "003",
      "DriverName": "Sarah",
      "Transporter": {
        "id": "T3",
        "number": "AN01030",
        "Company": "GlobalTrans"
      },
      "place": [
        { "id": 4, "name": "London" }
      ]
    }
  ]
};

// 筛选符合条件的行程
const filteredTrips = [];
// 遍历每个日期分组
for (const [date, journeys] of Object.entries(trips)) {
  // 遍历该日期下的每个行程
  const matchedJourneys = journeys.filter(journey => matchesSearchTerm(journey));
  if (matchedJourneys.length > 0) {
    filteredTrips.push({ date, journeys: matchedJourneys });
  }
}

console.log(filteredTrips);

代码说明

  • 递归函数matchesSearchTerm会处理所有嵌套层级:无论是数组里的子元素,还是对象里的属性值,都会被遍历检查。
  • 基础类型值会被转成字符串后和搜索数组比较,确保数字(比如journeyId、place.id)和字符串的匹配不会因为类型问题失效。
  • 最终filteredTrips会返回所有包含搜索项的行程,按日期分组保存。

比如上面的示例中,会匹配到:

  • 20180201下的第二个行程(包含AN01020和Trax)
  • 20180211下的所有行程(日期本身匹配搜索数组)

内容的提问来源于stack exchange,提问作者Udit Gogoi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:22:33