-1

So I have a folder tree that looks a bit like

- grandad
  - parent 1
    - ana
    - jack
    - david
  - parent 2
    - fred
    - lydia
    - david
  - parent 3
    - alfred
    - jo
    - david

...so every single parent folder has a child called david. What I want to do is to be able to traverse the tree from the grandad to one particular david and do something inside it without having to write n number of

while iterator.hasnext() { 
  const child = iterator.next() 
} 

as it can get pretty cumbersome if david happens to be a few levels down.

Is there a way to do this elegantly and avoiding repetition?

Thanks!

yago
  • 168
  • 1
  • 11

2 Answers2

1

If you know which folder you want then use DriveApp.getFolderById()

Cooper
  • 59,616
  • 6
  • 23
  • 54
  • Thanks @Cooper, but what I want is something I can reuse without knowing the ID of the folder because `grandad`, `parentX` and `david` will be variables, so I won't know the ID of the folder beforehand – yago Sep 09 '21 at 06:34
0

The best solution I have come up with, but which I'm sure can be improved upon, is using the following function:

function delveDeep(...args) { // so the number of arguments is indeterminate
  let folderIt = DriveApp.getFoldersByName(args[0]); // Grandpa folder iterator
  let child;

  for (let i = 1; i < args.length + 1; i++) {
    child = folderIt.next();
    if (i != args.length) {
      folderIt = child.getFoldersByName(args[i]);
    }
  }

  return child;
}

const destFolder = delveDeep(grandad, parentX, david);

This works for me for now, but I have to know the name of each of the folders that I have to traverse through in order to get to my david of interest.

I haven't seen any other way out but I'm not a very experience developer, so if anyone can improve upon this function, please do! :)

yago
  • 168
  • 1
  • 11