Skip to content

Instantly share code, notes, and snippets.

@vcpablo
Created July 8, 2021 15:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save vcpablo/ba8db39f72f6dd123a6c866004063c9b to your computer and use it in GitHub Desktop.
Save vcpablo/ba8db39f72f6dd123a6c866004063c9b to your computer and use it in GitHub Desktop.
Function that parses a flat tree structure with "parentId" and "order" to a strutcured data tree with "children"
const traverse = (arr, parentId) =>
arr.filter(node => node.parentId === parentId)
.reduce((result, current) => [
...result,
{
...current,
children: traverse(arr, current.id)
}
], [])
const parseTree = (arr) =>
arr.sort(({ order }) => order)
.filter(({ parentId }) => !parentId)
.map(node => ({
...node,
children: traverse(arr, node.id)
}))
// parseTree(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment