Skip to content

Instantly share code, notes, and snippets.

@zzzgydi
Last active March 17, 2022 06:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zzzgydi/93c4e5603503f5eda2d8e27daa8289c5 to your computer and use it in GitHub Desktop.
Save zzzgydi/93c4e5603503f5eda2d8e27daa8289c5 to your computer and use it in GitHub Desktop.
数组转树
const test = [
"./home/analysis",
"./home/boardTodo",
"./home/dairy",
"./home",
"./home/todo",
"./index",
"./profile"
];
function solve(array) {
const map = {};
array.forEach((each) => save(each));
return map['.']?.children;
function save(path) {
let current = map[path];
if (!current) {
current = { path: path.slice(1) };
map[path] = current;
}
const pathList = path.split('/');
pathList.pop();
if (pathList.length) {
const parent = save(pathList.join('/'));
if (!parent.children?.length) {
parent.children = [];
}
if (!parent.children.includes(current)) {
parent.children.push(current);
}
}
return current;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment