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

如何在递归嵌套数组中查找指定uuid对应元素的父节点

现有代码问题分析

  • 字段不匹配:代码中判断使用的id字段和实际数据中的唯一标识字段uuid不对应,匹配逻辑完全失效
  • 遍历提前终止:for循环中只要遇到带items属性的元素就直接返回递归结果,第一个title为2的section递归查询无结果后直接终止了整个遍历流程,不会向后查找title为3的section,导致返回错误结果
  • 缺少子元素匹配逻辑:没有对当前遍历的元素本身做目标id匹配,逻辑链路不符合需求

修正后代码

export const findItemParent = (items, targetUuid, parent = null) => {
  for (const item of items) {
    // 当前元素就是目标元素,直接返回对应父节点
    if (item.uuid === targetUuid) {
      return parent
    }
    // 存在子节点时递归查找
    if (Array.isArray(item.items) && item.items.length) {
      const matchResult = findItemParent(item.items, targetUuid, item)
      // 子节点中找到匹配结果直接返回
      if (matchResult) return matchResult
    }
  }
  // 全量遍历无匹配返回null
  return null
}

调用说明

调用方式和原有写法一致,传入包裹根节点的数组、目标元素的uuid即可:

const data = [/* 根节点数据 */];
const parent = findItemParent(data, "b2170580-1e2e-4fb4-a7b9-a56b79db21b3");

调用后返回的就是title为3的section元素,符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 19:06:03