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 trim(t: Tree, depth: number): Tree {
return {
...t,
children: depth ? t.children.map((c) => trim(c, depth - 1)) : [],
};
}
return trim(root, 1);
})(),
);
Sample output
{
label: 'src',
children: [ { label: 'app', children: [] }, { label: 'lib', children: [] } ]
}