将富文本编辑器中的H标签处理成树形结构,支持无限层级

做富文本编辑器时,需要将文本里的标题整理成树形数据,

// 这里是数据结构
const data = [
    {
        "id": "hkyrq2ndc-36yttda0lme00",
        "text": "阿萨德阿萨德阿萨",
        "level": 1,
        "depth": 1,
    },
    {
        "id": "h4kgw8yp6-5cjohrp4xek00",
        "text": "阿萨德阿萨德阿萨",
        "level": 3,
        "depth": 3,
    },
    {
        "id": "h4kgw8yp6-8yz253xo1ds00",
        "text": "阿萨德阿萨德阿萨",
        "level": 2,
        "depth": 2,
    },
    {
        "id": "h4kgw8yp6-98ln0anedx400",
        "text": "阿萨德阿萨德阿萨",
        "level": 1,
        "depth": 1,
    },
    {
        "id": "h4kgw8yp6-35frnwvulba000",
        "text": "胜多负少",
        "level": 2,
        "depth": 2,
    }
];

// 这里是是实现方法
function buildTree(data) {
    // 用来存储树形结构的根节点
    const root = [];

    // 用一个Map来存储每个节点,方便快速查找
    const map = new Map();

    // 当前处理的节点栈,用于维护父子关系
    const stack = [];

    // 遍历所有节点
    data.forEach(item => {
        // 初始化当前节点的子节点数组
        item.children = [];

        // 把当前节点添加到map中
        map.set(item.id, item);

        // 如果栈为空,说明是根节点
        if (stack.length === 0) {
            root.push(item);
            stack.push(item);
        } else {
            // 找到栈中最近的同级或更高级的节点
            while (stack.length > 0 && stack[stack.length - 1].level >= item.level) {
                stack.pop();
            }

            // 如果栈为空,说明是新的一组根节点
            if (stack.length === 0) {
                root.push(item);
            } else {
                // 否则,将当前节点添加到父节点的子节点数组中
                const parent = stack[stack.length - 1];
                parent.node.push(item);
            }

            // 将当前节点压入栈中
            stack.push(item);
        }
    });

    return root;
}


// 调用函数生成树形结构
const tree = buildTree(data);
console.log(JSON.stringify(tree, null, 2));

在这里插入图片描述

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值