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

如何编写递归方法在treeview节点列表中按ID查找项并更新数据

递归查找并更新树节点实现方案

核心逻辑

每个树节点默认包含唯一id、业务属性、以及存储子节点的children数组,递归实现逻辑如下:

  • 遍历当前层级的所有节点,比对节点id与目标id是否一致
  • 匹配成功则直接将新属性合并到目标节点,结束遍历
  • 当前节点未匹配时,若存在非空children数组则递归查找子节点
  • 子层级查找成功后直接终止所有层级的遍历,避免性能浪费

代码示例

JavaScript 版本

/**
 * 递归查找id匹配的节点并更新属性
 * @param {Array} treeList 树结构根节点数组
 * @param {string|number} targetId 要查找的目标节点id
 * @param {Object} newValues 要更新的属性键值对
 * @returns {boolean} 是否找到并更新了目标节点
 */
function updateTreeNodeById(treeList, targetId, newValues) {
  for (const node of treeList) {
    if (node.id === targetId) {
      // 合并新属性到目标节点
      Object.assign(node, newValues)
      return true
    }
    // 存在子节点则递归查找
    if (Array.isArray(node.children) && node.children.length > 0) {
      const isFound = updateTreeNodeById(node.children, targetId, newValues)
      if (isFound) return true
    }
  }
  // 全量遍历未找到目标节点
  return false
}

// 调用示例
const myTreeData = [/* 你的树节点数组 */]
// 更新id为1001的节点的name和disabled属性
const updateResult = updateTreeNodeById(myTreeData, 1001, {
  name: '更新后的节点名称',
  disabled: true
})

Python 版本

def update_tree_node_by_id(tree_list: list, target_id: int | str, new_values: dict) -> bool:
    for node in tree_list:
        if node['id'] == target_id:
            node.update(new_values)
            return True
        if 'children' in node and len(node['children']) > 0:
            is_found = update_tree_node_by_id(node['children'], target_id, new_values)
            if is_found:
                return True
    return False

注意事项

  • 上述实现为直接修改原树数据的版本,若需要保留原数据,可先对树结构做深拷贝后再调用方法
  • 若你的树结构中子节点数组的字段名不是children,将代码中对应的children替换为实际字段名即可
  • 如果存在id重复的节点,方法只会更新第一个匹配到的节点
  • 若用于Vue、React等框架的响应式树数据,该方法直接修改原对象属性的逻辑可正常触发视图更新,无需额外处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 20:36:01