Dev Helpers
← Back

Render a tree as nested paths

Render a tree as nested paths using TypeScript.

Open this example in the interactive library

Source code

type Tree = { label: string; children: Tree[] };
const root: Tree = {
  label: "src",
  children: [
    { label: "app", children: [{ label: "ui", children: [] }] },
    { label: "lib", children: [] },
  ],
};
console.log(
  (() => {
    function paths(t: Tree, prefix = ""): string[] {
      const path = prefix + "/" + t.label;
      return [path, ...t.children.flatMap((c) => paths(c, path))];
    }
    return paths(root);
  })(),
);

Sample output

[ '/src', '/src/app', '/src/app/ui', '/src/lib' ]