Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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