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

如何在JavaScript嵌套数组中查找目标对象?

获取嵌套数组中目标子对象的最优方法

先帮你理清现有代码的问题:

  • 第一个代码 bigArray.find(b => b.children.find(c=>c.City === 'city1')) 之所以返回父级元素,是因为内层的 children.find(...) 在找到匹配的子对象时会返回该子对象(属于真值),所以外层的 find 会把这个父级对象当作符合条件的结果返回,而不是你要找的子对象本身。
  • 第二个 bigArray.forEach(b => b.children.find(c=>c.City === 'city1')) 返回 undefined 是因为 forEach 方法本身没有返回值,哪怕内部的 find 找到了目标子对象,也不会被传递出来。

接下来给你几种最优的解决方案,根据你的需求选择:

1. 获取第一个匹配的目标子对象

方案A:用flatMap + find(简洁易读)

const targetChild = bigArray.flatMap(parent => parent.children).find(child => child.City === 'city1');

flatMap 会把所有父元素的 children 数组扁平成一个一维数组,之后直接用 find 定位到目标子对象,代码语义清晰,非常直观。

方案B:用reduce(性能更优,找到即停止)

如果你处理的数组很大,想要避免不必要的遍历,可以用 reduce:

const targetChild = bigArray.reduce((found, parent) => {
  // 如果已经找到目标,直接返回,不再继续遍历
  if (found) return found;
  // 在当前父元素的children中查找目标
  return parent.children.find(child => child.City === 'city1');
}, undefined);

这个方法会在找到第一个匹配的子对象后立刻停止遍历后续的父元素,性能上比 flatMap 更高效。

2. 获取所有匹配的目标子对象

如果需要找出所有 City 符合条件的子对象,用 flatMap + filter:

const allTargetChildren = bigArray.flatMap(parent => parent.children).filter(child => child.City === 'city1');

补充说明

  • 如果你的运行环境不支持 flatMap(比如旧版浏览器),可以用 concat 代替:[].concat(...bigArray.map(p => p.children)).find(...),效果和 flatMap 一致。
  • 这些方法都比嵌套循环更简洁,同时保持了良好的可读性和性能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:10:36