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

如何在深度嵌套数组中搜索并返回指定匹配结果?

解决方案

核心实现代码

const arr = [
  [
    {
      title: "title 1",
      city: [
        { "0": "London" },
        { "1": "LA" }
      ]
    },
    {
      title: "Title 2",
      city: [
        { "0": "New York" },
        { "1": "London" }
      ]
    }
  ],
  [
    {
      title: "Title 3",
      city: [
        { "0": "Paris" }
      ]
    },
    {
      title: "title 4",
      city: [
        { "0": "London" }
      ]
    }
  ]
];

const targetCity = "London";

const filteredArr = arr.map(subArr => {
  // 在当前子数组中找到第一个包含目标城市的对象
  const matchedItem = subArr.find(item => {
    // 检查当前对象的city数组是否存在目标值
    return item.city.some(cityObj => Object.values(cityObj)[0] === targetCity);
  });
  // 返回包含匹配对象的子数组(无匹配则返回空数组)
  return matchedItem ? [matchedItem] : [];
});

console.log(filteredArr);

代码逻辑解释

  • 保持层级结构:使用map遍历外层数组,确保最终结果和原数组的嵌套层级完全一致,不会扁平化结构。
  • 获取第一个匹配项:对每个子数组使用find方法,它会返回子数组中第一个满足条件的对象,精准匹配你“每个子数组仅返回第一个匹配对象”的需求。
  • 检查城市匹配:在find的判断逻辑中,用some遍历当前对象的city数组,通过Object.values(cityObj)[0]取出每个城市对象的实际值,和目标关键词对比,只要有一个匹配就判定当前对象符合条件。
  • 处理无匹配情况:如果某个子数组中没有符合条件的对象,会返回空数组;如果需要过滤掉这些空数组,可以在map后追加.filter(sub => sub.length > 0)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 00:21:26