树形结构获取路径名
Sunny-117 opened this issue · 3 comments
Sunny-117 commented
const treeData = [
{
name: "root",
children: [
{ name: "src", children: [{ name: "index.html" }] },
{ name: "public", children: [] },
],
},
];
const RecursiveTree = (data) => {
const res = []
const dfs = (data) => {
data.forEach(ele => {
res.push(ele.name)
ele.children && dfs(ele.children)
});
}
dfs(data)
return res;
}
console.log(RecursiveTree(treeData));
zzyyhh22lx commented
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' ]
kangkang123269 commented
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;
}
bearki99 commented
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);