code: private function recursiveMenuItemHandling(Collection $menuItems) {
          $data = [];
          foreach($menuItems as $menuItem) {
              // This is necessary to avoid to loop on children only when already included as previous parent children
              if(!in_array($menuItem->getId(), $this->alreadySetIds)) {
                  $this->alreadySetIds[] = $menuItem->getId();
                  $itemNode = [];
                  $itemNode['name'] = $menuItem->getTitle();
                  $itemNode['url'] = $menuItem->getTarget();
                  $itemNode['id'] = $this->position;
                  $itemNode['persist_id'] = $menuItem->getId();
                  if(null === $menuItem->getParent()) {
                      $itemNode['owner_type'] = get_class($this->currentOwner);
                      $itemNode['owner_id'] = $this->currentOwner->getId();
                  }
                  $this->position++;
                  if ($menuItem->getChildren()->count() > 0) {
                      $itemNode['children'] = $this->recursiveMenuItemHandling($menuItem->getChildren());
                  }
                  $data[] = $itemNode;
              }
          }
  
          return $data;
      }
docs: Recursive method to handle tree nested menus
  @param Collection $menuItems
  @return array