When working with a multi-node tree, adding a new row often requires obtaining the reference of that specific row by its id in order to trigger the rowclick event programmatically.
In this scenario, if a row with the id 9 needs to be added, the challenge lies in iterating through the tree structure to reach this particular node.
It's worth noting that the nesting of children nodes within other children nodes can be infinite, creating complex parent-child relationships.
Consider the following example:
let data = [{
"id": 1,
"name": "parent 1"
}, {
"id": 2,
"name": "parent 2",
"children": [{
"id": 5,
"name": "parent-children 5",
},{
"id": 6,
"name": "parent-children 6",
"children": [{
"id": 7,
"name": "parent-children-children 7",
},{
"id": 8,
"name": "parent-children-children 8",
"children": [{
"id": 9,
"name": "parent-children-children-children 9",
},{
"id": 10,
"name": "parent-children-children-children 10",
}]
}]
}]
}, {
"id": 3,
"name": "parent 3"
}, {
"id": 4,
"name": "parent 4"
}]
To navigate through levels one and two of the nodes, you may consider implementing the following iteration function:
getItemRow(id){
//If it is a parent node
let myItem = this.parents.find(parent => parent.id === id);
if(myItem !== undefined){ return myItem }
//If it is a second-level children node (parent-children)
this.parents.forEach(function(parent){
let child = parent.children.find(child => child.id === id);
if(child !== undefined){ return child }
});
}