After spending hours searching on various forums for a solution to my problem, I have yet to find one that directly addresses the issue I am facing. So, please take a moment to review the details below.
The object structure in question is as follows:
let data = [{
"id": 777,
"name": "Level 1_section_1",
"children": [{
"id": 778,
"name": "Level 2a",
"children": [
]
},
{
"id": 783,
"name": "Level 2b",
"children": [
]
}
]
},
{
"id": 786,
"name": "Level 1_section_2",
"children": [{
"id": 781,
"name": "Level 2c",
"children": [
]
}]
}
]
In essence, each node's children property contains an array of nodes with the same structure.
If I want to locate the node with id:783
, my first instinct would be to implement recursion. However, I am unsure how to ensure that this recursive function traverses the entire tree until it locates and returns the specific node I require so that I can add more children to it.
Although I come from a computer science background, my understanding of recursion is somewhat lacking.
This is the attempted solution I have implemented in my jsfiddle: https://jsfiddle.net/hanktrizz/surmf7dq/4/
Please bear in mind that the depth of the data
tree may vary (although it should not exceed 8 or 9 levels) but I wanted to highlight this nonetheless.