<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
let treeDTO = [];
const baseData = ["a/b/c/d/e", "a/b/e/f/g", "a/b/h", "a/i/j", "a/i/k"];
baseData.forEach((item) => {
const nodeArray = item.split("/");
let children = treeDTO;
for (let label of nodeArray) {
let obj = {
label: label,
};
if (children.length === 0) {
children.push(obj);
}
let isExist = false;
for (let index in children) {
if (children[index].label === label) {
if (!children[index].children) {
children[index].children = [];
}
children = children[index].children;
isExist = true;
break;
}
}
if (!isExist) {
children.push(obj);
if (!children[children.length - 1].children) {
children[children.length - 1].children = [];
}
children = children[children.length - 1].children;
}
}
});
console.log(treeDTO);
</script>
</body>
</html>
字符串路径递归
最新推荐文章于 2026-07-01 12:03:20 发布
这段代码展示了如何从一组路径字符串(如a/b/c/d/e)创建一个树形数据结构。它遍历每个路径,将路径拆分成节点,并在现有树结构中找到合适的位置插入这些节点,构建出一个多级目录的表示。
177

被折叠的 条评论
为什么被折叠?



