score:0

Accepted answer

You are not using find properly. If you return anything truthy in its callback, it will return the current element.

this.getSelectedNode(element.nodes) will eventually return the right element, but it will be treated as a truthy value, and it will mean that no matter what you do, the first element will be returned if any of it's descendants it's a match.

What you want to do is something like this:

getSelectedNode(nodes) {
  // Use a for loop instead of forEach to avoid nested functions
  // Otherwise "return" will not work properly
  for (const element of nodes) {
    // Check if this element is the seleted one, return it if it is
    if(element.name === this.state.selectedItem) {
       return element
    }

    // If it's not - recursively check its descendants, if it has any
    if(element.nodes){
      const found =  this.getSelectedNode(element.nodes)

      if(found){
       return found
      }
    }
  }

  // didn't find anything, return null
  return null
}

Related Query

More Query from same tag