Dev Helpers
← Back

Transform labels without mutating the tree

Transform labels without mutating the tree 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 upper(t: Tree): Tree {
      return { label: t.label.toUpperCase(), children: t.children.map(upper) };
    }
    return upper(root);
  })(),
);

Sample output

{
  label: 'SRC',
  children: [
    { label: 'APP', children: [Array] },
    { label: 'LIB', children: [] }
  ]
}