-
-
Notifications
You must be signed in to change notification settings - Fork 235
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
树形结构获取路径名 #39
Comments
const treeData = [
{
name: "root",
children: [
{ name: "src", children: [{ name: "index.html" }] },
{ name: "public", children: [] },
],
},
];
// 树形结构获取路径名
const RecursiveTree = (data) => {
return data.reduce((pre, cur) => {
cur.name && pre.push(cur.name);
cur.children && pre.push(...RecursiveTree(cur.children));
return pre;
}, []);
}
console.log(RecursiveTree(treeData)); // [ 'root', 'src', 'index.html', 'public' ] |
function getNodePath(root, target) {
if (!root) {
return null;
}
if (root === target) {
return [root.name];
}
for (const child of root.children) {
const path = getNodePath(child, target);
if (path) {
return [root.name, ...path];
}
}
return null;
} |
const res = [];
function getName(arr) {
arr.forEach((obj) => {
if (obj.name) res.push(obj.name);
if (obj.children) getName(obj.children);
});
}
const treeData = [
{
name: "root",
children: [
{ name: "src", children: [{ name: "index.html" }] },
{ name: "public", children: [] },
],
},
];
getName(treeData);
console.log(res); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The text was updated successfully, but these errors were encountered: