【路径规划】混合人工蜂群ABC和粒子群优算法PSO机器人路径规划【含Matlab源码 14774期】
2025/12/24 18:17:50
在Web开发中,我们经常需要处理树形结构数据(如组织架构、分类目录、菜单等)。今天我将分享一个实用的JavaScript方法,用于在复杂的树形数据结构中根据ID查找对应的节点标签。
/** * 根据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; }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" } ] } ];// 查找存在的节点 const node = findLabelById(111, treeData); console.log(node); // 输出:{ id: 111, label: "节点1-1-1" } // 查找不存在的节点 const notFound = findLabelById(999, treeData); console.log(notFound); // 输出:null