深度优先遍历: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
相关推荐
于慨1 天前
Lambda 表达式、方法引用(Method Reference)语法
java·前端·servlet
石小石Orz1 天前
油猴脚本实现生产环境加载本地qiankun子应用
前端·架构
从前慢丶1 天前
前端交互规范(Web 端)
前端
@yanyu6661 天前
07-引入element布局及spring boot完善后端
javascript·vue.js·spring boot
‎ദ്ദിᵔ.˛.ᵔ₎1 天前
LIST 的相关知识
数据结构·list
CHU7290351 天前
便捷约玩,沉浸推理:线上剧本杀APP功能版块设计详解
前端·小程序
GISer_Jing1 天前
Page-agent MCP结构
前端·人工智能
王霸天1 天前
💥别再抄网上的Scale缩放代码了!50行源码教你写一个永不翻车的大屏适配
前端·vue.js·数据可视化
小领航1 天前
用 Three.js + Vue 3 打造炫酷的 3D 行政地图可视化组件
前端·github
@大迁世界1 天前
2026年React大洗牌:React Hooks 将迎来重大升级
前端·javascript·react.js·前端框架·ecmascript