'React: How to traverse through all children nodes in the tree view structure?
I am working with react-expandable-treeview structure for displaying a family tree data. With the following code, I am traversing through the items object with family tree data, storing it into const data and then recursively passing into TreeView like it is indicated in documentation of react-expandable-treeview:
const items = props.item;
var x = 0;
const data = [{
id: x,
label: items.first_name, // parent #1
children: items.children.map( (child, idx) => {
id: x= ++idx,
label: child.first_name, // child of parent #1
children: child.children.map( (child_child) => ({
id: x = ++idx,
label: child_child.first_name,
children: child_child.children
? child_child.children.map( (child_child_child) => ({
id: x = ++idx,
label: child_child_child.first_name,
children: child_child_child.children
}))
: null
}))
}))
}]
However, with the algorithm above, I was able to only get the root node, its children, and two more generations of the family. This is a screenshot of how the structure looks like, it shows the amount of the nodes and their relationships correctly, but their indexes and first names are not displayed correctly.
I can't figure out how to perform the last mapping function, so that
id: x = ++idx,
label: the_rest_of_children.first_name,
children: the_rest_of_children.children
worked for the rest of children and expanded all nodes children until the very last node. How can I fix my code to get the correct output?
Solution 1:[1]
Use recursion
let index = 0
function visit(node) {
return {
label: node.first_name,
id: index++,
// pass `visit` function as an argument
children: node.children.map(visit)
}
}
const data = visit(props.items)
Recursion isn't the only way to traverse tree-like structures. If your tree is extremely complex, it'd be safer to implement iterative traversal algorithm:
If the recursive implementation is so simple, why bother with an iterative one? Of course, to avoid stack overflow. Most runtime engines/compilers set a limit on how many nested calls a program can make. If the height of the tree is larger than this limit, the program will crash with a stack overflow error. ...
But those cases aren't common in web development.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | evilsiner |
