做富文本编辑器时,需要将文本里的标题整理成树形数据, // 这里是数据结构 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));