Skip to content
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

Open
Sunny-117 opened this issue Nov 3, 2022 · 3 comments
Open

树形结构获取路径名 #39

Sunny-117 opened this issue Nov 3, 2022 · 3 comments

Comments

@Sunny-117
Copy link
Owner

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
Copy link

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
Copy link

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
Copy link

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
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants