Home > Blockchain >  ForEach loop to combine data from 2 adjacent columns
ForEach loop to combine data from 2 adjacent columns

Time:09-02

I'm using a script to generate named files based on spreadsheet data (ref. here: https://www.bazroberts.com/2021/07/10/multiple-file-maker/). Basically, it makes copies of a target file, and renames those copies based on data from a range on the sheet.

The script creates filenames based on the data in a target column (variableNames). I'm trying to create those filenames based on the data from TWO target columns, adding a document ID number from an adjacent column to the variable name (so filename = docID " " variableName... e.g. "1.2 DocumentName").

I've got the correct ranges captured and stored:

let variableNames = shFiles.getRange(1, 3)
  .getDataRegion(SpreadsheetApp.Dimension.ROWS)
  .getDisplayValues();
let docIds = shFiles.getRange(1, 2)
  .getDataRegion(SpreadsheetApp.Dimension.ROWS)
  .getDisplayValues();
variableNames.splice(0, 2);
docIds.splice(0, 2);

What I can't figure out is how to tweak the forEach function that creates the filenames to use both variable pieces of data at a time. Here's the version with one piece of data for reference:

//Extract file ID and get master file 
const masterFile = DriveApp.getFileById(fileId);

//Copy master for each of the variable names
//and rename each copy with the fixed and variable name 
variableNames.forEach((variableName) => {
  masterFile.makeCopy(variableName);
})

I had tried nested forEach, but that ended up doing a recursive thing where I basically had every combination of docID and variableName, instead of just the aligned pairs. Maybe I should be using for instead of forEach?

CodePudding user response:

constructing names

function lfunko() {
  const ss = SpreadsheetApp.getActive();
  const masterFile = DriveApp.getFileById("fileId");
  const sh = ss.getSheetByName("sheetname");
  const vs = sh.getRange(3, 3, sh.getLastRow() - 2, 2).getDisplayValues();
  vs.forEach(r => {
    let id = r[0];
    let n = r[1];
    masterFile.makeCopy(`${id} ${n}`);
  });
}
  • Related