Looping on FolderIterator and FileIterator - Google Apps Script

Viewed 672

I'm making a script to loop in a Google Drive folder and noticed I don't know what's the best way to loop over iterators (specifically FolderIterator and FileIterator). My first approach

const drive_id  = '__________';
let base_folder = DriveApp.getFolderById(drive_id),
    sub_folders = base_folder.getFolders();
Logger.log(base_folder.getFolders());
for(let sub_folder of sub_folders) 
{
    Logger.log(sub_folder);
}

outputs Error TypeError: sub_folders is not iterable.

Secondly I tried with while loops and checks on hasNext(), but I didn't find them beautifyl enough. I'm currently set with this for loop, that works and is clean enough but still looks a bit hacky.

/*...*/
for(let sub_folders = base_folder.getFolders(); sub_folders.hasNext();)
{
  let sub_folder = sub_folders.next();
  Logger.log(sub_folder);
}

Also notice how I couldn't declare sub_folder within the loop itself. So, what's the proper way of doing it?

Also, what if I wanted to use a map or filter on the sub_folders instead?

Note: this question is probably of broader scope than google-script, but I couldn't find the right terminology to ask the question differently so I preferred to stick to the particular case I found.

1 Answers

What's the proper way of looping a FolderIterator or FileIterator?

  • The proper way of doing it by using a while loop.

  • The reason for that has to do with the hasNext() function which returns a Boolean (true or false) and the only loop that natively works with booleans is the while loop.

Also, what if I wanted to use a map or filter on the sub_folders instead?

  • In your code sub_folder is an object of type Folder. Unfortunately, you can only retrieve the folders one by one within the while loop by using next() so you can't directly apply map or filter on the FolderIterator.

  • Instead, you can create an array of folders by pushing each folder to an array (within the while loop) and then use map.

Example:

This script finds all the folders and store them in an array and then uses map to get the name of each sub folder:

function myFunction() {
  const base_folder  = DriveApp.getFolderById('folder_id');
  const sub_folders  = base_folder.getFolders();
  const folders = [];

  while (sub_folders.hasNext()){
    let folder = sub_folders.next()
    folders.push(folder);
  }
  
  const folder_names = folders.map(f=>f.getName());
  console.log(folder_names);
} 

Here is a list of all the available methods you can apply to each element of the folders array: Class Folder

Related