Dev Helpers
← Back

Find a node by label

Find a node by label 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 find(t: Tree, key: string): Tree | undefined {
      if (t.label === key) return t;
      for (const c of t.children) {
        const match = find(c, key);
        if (match) return match;
      }
    }
    return find(root, "ui")?.label;
  })(),
);

Sample output

ui