Skip to content

Instantly share code, notes, and snippets.

@nicksheffield
Created March 20, 2023 02:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicksheffield/bb4a3c6dc680d8d4277cb315c147cd97 to your computer and use it in GitHub Desktop.
Save nicksheffield/bb4a3c6dc680d8d4277cb315c147cd97 to your computer and use it in GitHub Desktop.
turn flat structure into nested structure
type Item = {
id: string
parentId: string | undefined
}
type NestedItem = Item & {
children: NestedItem[]
}
const getNestedItems = (items: Item[], parentId: string | undefined = undefined) => {
return items
.filter((x) => x.parentId === parentId)
.map<NestedItem>((x) => ({ ...x, children: getNestedItems(items, x.id) }))
}
console.log(JSON.stringify(getNestedItems([
{ id: '1', parentId: undefined },
{ id: '2', parentId: '1' },
{ id: '3', parentId: '2' },
{ id: '4', parentId: '1' },
]), null, 4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment