Swap between children of children objects

I’m trying to swap between children of objects. I need to show only the selected objects. But I’m facing some issues when it comes to children of children object.

My code:

function swapObjects(objectName) {
  parentObject.traverse((child) => {
      if (
        child.name == objectName &&
        child.userData.canSwap == true
      ) { if(child.parent.visible == true){
          child.visible = true
        }else child.visible = false     
      } else {
        if (child.userData.canSwap == true) {
          child.visible = false;

Since I traverse the parent object every time the function is called, the parent also gets hidden when the name is not true. How can I use the parent-child relationship effectively to achieve this?