JS通过递归函数来剔除树结构特定节点

最近在处理权限类问题过程中,遇到多次需要过滤一下来列表的数据,针对不同用户看到的数据不同。记录一下

我的数据大致是这样的:

javascript 复制代码
class UserTree {
    constructor() {
        this.userTreeData = [
            // 示例数据
            { nodeid: "1", nodename: "Root", parentid: null, children: [
                { nodeid: "2", nodename: "Child 1", parentid: "1", children: [] },
                { nodeid: "3", nodename: "Child 2", parentid: "1", children: [
                    { nodeid: "67176000000000000000000000000000", nodename: "Grandchild 1", parentid: "3", children: [] },
                    { nodeid: "4", nodename: "Another Grandchild", parentid: "3", children: [
                        { nodeid: "67176000000000000000000000000001", nodename: "Great Grandchild", parentid: "67176000000000000000000000000000", children: [] }
                    ] }
                ] }
            ] }
        ];
    }

    // 递归函数来剔除特定节点以及parentid为特定值的节点
    removeNodeByIdAndParentId(tree, nodeId) {
        if (!tree || tree.length === 0) return;

        for (let i = 0; i < tree.length; i++) {
            if (tree[i].nodeid === nodeId || tree[i].parentid === nodeId) {
                tree.splice(i, 1); // 删除节点
                i--; // 更新索引以继续检查下一个元素
            } else if (tree[i].children && tree[i].children.length > 0) {
                // 递归遍历子节点
                this.removeNodeByIdAndParentId(tree[i].children, nodeId);
            }
        }
    }

    // 初始化用户树数据
    initUserTreeData() {
        // 需要剔除的节点ID
        const targetNodeId = "67176000000000000000000000000000";

        // 调用递归函数来剔除节点
        this.removeNodeByIdAndParentId(this.userTreeData, targetNodeId);

        // 继续其他初始化逻辑...
    }
}

// 测试
let userTree = new UserTree();
console.log("Before removal:", JSON.stringify(userTree.userTreeData, null, 2));
userTree.initUserTreeData();
console.log("After removal:", JSON.stringify(userTree.userTreeData, null, 2));
  1. 递归函数 removeNodeByIdAndParentId :这个函数会检查每个节点,如果节点的 nodeidparentid 为目标节点ID,则将该节点及其子节点一并删除。
  2. 递归调用 :在删除当前节点后,更新索引(i--),以便继续检查下一个元素。这样可以确保不会跳过任何元素。
  3. 初始化函数 initUserTreeData:在初始化函数中调用递归函数来剔除目标节点及其子节点。
相关推荐
米丘9 小时前
React 19.x 的 lazy 与 Suspense
前端·javascript·react.js
一然明月10 小时前
qt基本用法
开发语言·qt
hef28810 小时前
Prism图形设计从入门到精通:外观设置、图层顺序与微调技巧
开发语言
ZC跨境爬虫10 小时前
跟着 MDN 学CSS day_21:(图像溢出控制与表单元素样式定制)
前端·javascript·css·ui·交互
长谷深风11110 小时前
Java 面试高频:反射机制与异常体系全面解析
java·开发语言·面试·exception·java 反射·java 异常·class 对象
riuphan11 小时前
JavaScript 中的 this 关键字
javascript
掰头战士11 小时前
五分钟带你深入了解 this
javascript
fantasy_arch11 小时前
BasicVSR-lite图像画质增强
开发语言·pytorch
biubiubiu_LYQ11 小时前
萌新小白基础理解篇之 this 关键字
前端·javascript
甜味弥漫11 小时前
深度解析 JS 中的 this 指向:从底层逻辑到实战规则
javascript·面试