Google Apps 脚本:根据值对多个变量使用 getFolderById

Google Apps Script: Use getFolderById for multiple variables depending on value

我认为 Google Apps 脚本存在一个非常简单的问题,但我已经尝试 google 解决方案 1.5 小时但没有成功。我想我搜索了错误的术语。

这是我的代码:

function folderLocations(){
  var folder = {
    Michael: '1bz9wIBRcRN2V-xxxxxxxxxx',
    Chris: '1AEKHiI8iZKjHs-xxxxxxxxxx',
    Steve: '1TD8iwjcbR7K5dN-xxxxxxxxxx',
  };
  return folder;
}

function createNewGoogleDocs() {

  //ID of Google Docs Template, what sheet to use + save all values as 2D array
  const googleDocTemplate = DriveApp.getFileById('xxxxxxxxxx_XznDn-i0WVtIM');
  const sheet = SpreadsheetApp
    .getActiveSpreadsheet()
    .getSheetByName('Current Overview');
  const rows = sheet.getDataRange().getValues();
  
  //Start processing each spreadsheet row
  rows.forEach(function(row, index){
    
    //Destination folder ID (can differ from each person)
    const destinationFolder = DriveApp.getFolderById(folderLocations().Chris);

    // Set custom file name and create file
    const copy = googleDocTemplate.makeCopy(`${row[15]} - ${row[3]} Quarterly Review` , destinationFolder);
    const doc = DocumentApp.openById(copy.getId());
    const body = doc.getBody();
    
    // Replace placeholders with real values
    body.replaceText('%NAME%', row[3]);
    body.replaceText('%QUARTER%', row[15]);
    body.replaceText('%ANSWER_1%', row[16]);
    body.replaceText('%ANSWER_2%', row[17]);
    [...]
    doc.saveAndClose();
    
  })
}

一切正常!但是:我想要的是根据单元格的值“动态”更改文件夹。并不总是“克里斯”...:[=​​14=]

const destinationFolder = DriveApp.getFolderById(folderLocations().Chris);

例如:如果行[4] == Michael,则使用“Michael”的文件夹 ID。不知何故,我无法让它“动态地”工作。

我已经尝试了所有这些,none 工作:

const destinationFolder = DriveApp.getFolderById(folderLocations().row[4]);
const destinationFolder = DriveApp.getFolderById(folderLocations(row[4]));
const destinationFolder = DriveApp.getFolderById(folderLocations().`${row[4]}`);
const destinationFolder = DriveApp.getFolderById(folderLocations().toString(row[4]));
etc.

我知道我在这里尝试做的事情很尴尬。但我通常不是开发人员,我公司没有人熟悉 Google Apps 脚本。这是我遗漏的最后一点,剩下的我自己用 Google.

组合在一起

非常感谢!

这成功了:

function folderLocations(person){
  var folder = {
    Michael: '1bz9wIBRcRN2V-xxxxxxxxxx',
    Chris: '1AEKHiI8iZKjHs-xxxxxxxxxx',
    Steve: '1TD8iwjcbR7K5dN-xxxxxxxxxx',
  };
  return folder[person];
}

...进一步如下:

const destinationFolder = DriveApp.getFolderById(folderLocations(row[4]));

你甚至不需要函数。一个对象就够了:

const folderLocations = {
    Michael: '1bz9wIBRcRN2V-xxxxxxxxxx',
    Chris: '1AEKHiI8iZKjHs-xxxxxxxxxx',
    Steve: '1TD8iwjcbR7K5dN-xxxxxxxxxx',
};

var id = folderLocations['Chris'];

console.log(id); // 1AEKHiI8iZKjHs-xxxxxxxxxx

const destinationFolder = DriveApp.getFolderById(folderLocations[row[4]]);