How should I approach the problem of saving a file to a specific folder depending on the result of a variable?
For example,
Say I have 3 clients Bob, Billy and Ben. And on google drive, I have corresponding folders for each client, so "BobFolder", "BillyFolder" and "BenFolder".
If the name happens to be "Bob" during a loop, then I would like to save my file to "BobFolder". Since I am using DriveApp.getFolderById(), I am thinking the only approach is to use switch statements (or similar logic) using the folder IDs. Or is there another way to do this?
Appreciate any help I can get!
Here is roughly how I would grab the client name from my google sheet:
// get data range
const rows = invSh.getDataRange().getValues();
var toIndex = getColumnId(invSh, "To") - 1;
rows.forEach(function (row, index) {
// skip header row logic
// skip rows that already have document created and linked logic
// make copy document of template and get body (this is also where i would add logic to figure out the destination folder depending on the client)
const copy = googleDocTemplate.makeCopy(`INVOICE_${row[invNumIndex]}`, destinationFolder);
const doc = DocumentApp.openById(copy.getId());
const body = doc.getBody();
// add client name to doc
body.replaceText('{{to}}', row[toIndex]);
}
So during the loop, each row will call row[toIndex] which would could for example be:
row[0] -> 'Bob'
row[1] -> 'Billy'
etc.
Do you mean something like this?
var IDs = {
'Bob': 'ID-1',
'Bill': 'ID-2',
'Ben': 'ID-3',
}
var folder_id = IDs['Bill'];
console.log(folder_id); // output: ID-2
var the_name = 'Bob';
folder_id = IDs[the_name];
console.log(folder_id); // output: ID-1
And you can use:
var dest_folder = DriveApp.getFoldersByName('BobFolder').next();
But make sure that you have just one folder with name 'BobFolder' on your Drive. Otherwise the result could be random. This is why to use ID is a better idea.