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:在初始化函数中调用递归函数来剔除目标节点及其子节点。
相关推荐
for_ever_love__10 分钟前
PySpark学习: 数据输出
开发语言·python·学习·spark
言乐621 分钟前
Python实现自动拉人脚本示例
开发语言·windows·python·django·pygame
啊啊啊啊啊!!!!23 分钟前
【c++】二叉搜索树
开发语言·c++
归去来 兮41 分钟前
Python爬虫爬取数据案例
开发语言·爬虫·python
ShineWinsu43 分钟前
对于 C++:C++20中Concept(概念) 与 Coroutine(协程)的解析
linux·开发语言·网络·c++·c++20·epoll
ly768944 分钟前
C 语言从入门到进阶:语法、指针、内存管理与工程实践详解
c语言·开发语言
quantdash_cc1 小时前
历史数据断层与REST请求慢到崩溃?QuantDash高性能量化数据API终极解决方案
开发语言·python·缓存·php·量化·quantdash
breeze jiang1 小时前
Next.js 16 App Router 实战:从 About、Blog 动态路由到全局 404
开发语言·javascript·ecmascript
熊野君1 小时前
Prompt / RAG / 规则 / Skills —— 定位、协作与实现路线
开发语言·python
山甫aa2 小时前
JavaWeb后端开发学习手册
java·开发语言·数据库·学习·mysql·springboot·web