Created
March 20, 2023 02:29
-
-
Save nicksheffield/bb4a3c6dc680d8d4277cb315c147cd97 to your computer and use it in GitHub Desktop.
turn flat structure into nested structure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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