深度优先遍历:JavaScript递归查找树形数据结构中的节点标签

概述

在Web开发中,我们经常需要处理树形结构数据(如组织架构、分类目录、菜单等)。今天我将分享一个实用的JavaScript方法,用于在复杂的树形数据结构中根据ID查找对应的节点标签。

核心算法

javascript 复制代码
/**
 * 根据id在树形数据结构中查找对应的节点
 * @param {string|number} id - 要查找的节点ID
 * @param {Array|Object} data - 树形数据结构(数组或对象)
 * @returns {Object|null} 找到返回完整的节点对象,找不到返回null
 */
findLabelById(id, data) {
  // 边界条件处理:如果data为空或未定义,直接返回null
  if (!data) {
    return null;
  }

  // 情况1:data是数组(树的根节点或子节点数组)
  if (Array.isArray(data)) {
    for (let i = 0; i < data.length; i++) {
      const result = this.findLabelById(id, data[i]);
      if (result !== null) {
        return result;
      }
    }
    return null;
  }

  // 情况2:data是对象(单个节点)
  if (data && typeof data === 'object') {
    // 如果当前节点的id匹配目标id,返回当前节点
    if (data.id === id) {
      return data;
    }

    // 如果当前节点有子节点,递归查找子节点
    if (data.children && Array.isArray(data.children) && data.children.length > 0) {
      for (let i = 0; i < data.children.length; i++) {
        const result = this.findLabelById(id, data.children[i]);
        if (result !== null) {
          return result;
        }
      }
    }
  }

  // 未找到匹配的节点
  return null;
}

使用示例

javascript 复制代码
const treeData = [
  {
    id: 1,
    label: "节点1",
    children: [
      {
        id: 11,
        label: "节点1-1",
        children: [
          { id: 111, label: "节点1-1-1" },
          { id: 112, label: "节点1-1-2" }
        ]
      },
      { id: 12, label: "节点1-2" }
    ]
  },
  {
    id: 2,
    label: "节点2",
    children: [
      { id: 21, label: "节点2-1" }
    ]
  }
];

查找示例

javascript 复制代码
// 查找存在的节点
const node = findLabelById(111, treeData);
console.log(node); // 输出:{ id: 111, label: "节点1-1-1" }

// 查找不存在的节点
const notFound = findLabelById(999, treeData);
console.log(notFound); // 输出:null
相关推荐
AI视觉网奇6 分钟前
Uncaught SyntaxError: Failed to construct ‘RTCPeerConnection‘:
前端·javascript·html
再学一点就睡7 小时前
前端网络实战手册:15个高频工作场景全解析
前端·网络协议
D_FW8 小时前
数据结构第六章:图
数据结构·算法
C_心欲无痕8 小时前
有限状态机在前端中的应用
前端·状态模式
C_心欲无痕8 小时前
前端基于 IntersectionObserver 更流畅的懒加载实现
前端
candyTong8 小时前
深入解析:AI 智能体(Agent)是如何解决问题的?
前端·agent·ai编程
柳杉8 小时前
建议收藏 | 2026年AI工具封神榜:从Sora到混元3D,生产力彻底爆发
前端·人工智能·后端
weixin_462446238 小时前
使用 Puppeteer 设置 Cookies 并实现自动化分页操作:前端实战教程
运维·前端·自动化
CheungChunChiu8 小时前
Linux 内核动态打印机制详解
android·linux·服务器·前端·ubuntu
Irene19919 小时前
Vue 官方推荐:kebab-case(短横线命名法)
javascript·vue.js