Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Iterate through nested arrays of objects with an undetermined number of children node levels

In a multi-node tree, when I add a new row, I need to get the reference of that row, by its id, to fire the rowclick event programmatically.

In the following example, if I add the row with id 9, how to iterate through the tree to this node.

Note: children of children nodes are unlimited (for example: parent-children-children-children-children-children… )

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Tree 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"
}]

Iteration on levels one and two of the nodes

getItemRow(id){
    //If is a parent node
    let myItem = this.parents.find(parent => parent.id === id);
    if(myItem !== undefined){ return myItem }

    //If 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 }

    });
}

>Solution :

We can recursively search all nodes until we find the match:

getItemRow(id){
    return findNodeWithId(id, this.parents)
}

findNodeWithId(id, rootArr) {
  for (let el of rootArr) {
    if (el.id === id) {
      return el
    }
    if (el.children) {
        const idFoundInChildren = findNodeWithId(id, el.children)
        if (idFoundInChildren !== null) {
          return idFoundInChildren
        }
    }
  }
  return null
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading