做富文本编辑器时,需要将文本里的标题整理成树形数据,
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 = [];
const map = new Map();
const stack = [];
data.forEach(item => {
item.children = [];
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));
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/ab7394e917bc42f0a0a5715883c6403b.jpeg)