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

如何通过名称路径在嵌套对象数组中查找目标对象?

解决嵌套对象数组的路径查找问题

我来帮你搞定这个路径查找的问题!你的递归实现里有个关键bug:在处理多层路径时,find方法需要返回布尔值来判断是否匹配,但你直接返回了递归调用的结果(一个对象)——这会让find误以为只要子层级能找到匹配项,当前节点就是目标,最终返回的是父节点而非你要的深层节点。

先修复你的递归版本

我们调整逻辑,明确先找到当前层级的匹配节点,再递归处理剩余路径:

function getObjectByNamePath(path, fields) {
  const [currentName, ...restPath] = path.split('.');
  // 找到当前层级的匹配节点
  const match = fields.find(field => field.name === currentName);
  if (!match) return null; // 没找到直接返回null
  // 还有剩余路径就递归查子节点,否则返回当前匹配项
  return restPath.length ? getObjectByNamePath(restPath.join('.'), match.childFields) : match;
}

更优雅的迭代实现(推荐)

递归在路径极深时可能有栈溢出风险,用reduce实现更稳妥简洁,一行核心逻辑就能搞定:

function getObjectByNamePath(path, fields) {
  return path.split('.').reduce((currentScope, name) => {
    if (!currentScope) return null;
    return currentScope.find(field => field.name === name);
  }, fields);
}

测试验证

用你的示例数据测试:

var obj = [
  { name: 'ob_1', childFields: [] },
  { name: 'ob_2', childFields: [
    { name: 'ob_2_1', childFields: [
      { name: 'ob_3_1', childFields: [], test: 124 }
    ] }
  ] }
];

console.log(getObjectByNamePath('ob_2.ob_2_1.ob_3_1', obj));
// 输出:{ name: 'ob_3_1', childFields: [], test: 124 }

这个reduce版本的逻辑很清晰:把路径拆分成名称数组,每次从当前的字段集合(初始是根数组)里找到匹配名称的节点,然后把下一次的currentScope更新为该节点的childFields,直到遍历完所有路径段,最终返回的就是目标对象;如果中途找不到匹配项,就直接返回null。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:16:34