Function that parses a flat tree structure with "parentId" and "order" to a strutcured data tree with "children"
This file contains 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
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