Home > Software design >  How can I use dynamic variable numbers in a loop?
How can I use dynamic variable numbers in a loop?

Time:07-27

I created a little tool that allows us to use a G sheet as the source for a G doc template. Essentially, it takes the values from the G sheet and replaces the placesholders in the template with the respective values.

Here I am declaring the variables:

  var MB_1 =  ws.getRange("C1").getValue();

And here I am replacing the document's body text with the respective values:

  var docBody = DocumentApp.openById(createdFileId).getBody();
  docBody
  .replaceText("{mbd_1}", MB_1) 

The thing is that I have 300 variables and I want to avoid having something like this:

var docBody = DocumentApp.openById(createdFileId).getBody();
  docBody
  .replaceText("{mbd_1}", MB_1) 
  .replaceText("{mbd_2}", MB_2) 
  .replaceText("{mbd_3}", MB_3) 
  .replaceText("{mbd_4}", MB_4) 
  .replaceText("{mbd_5}", MB_5) 
  .replaceText("{mbd_6}", MB_6) 
  .replaceText("{mbd_7}", MB_7) 
  .replaceText("{mbd_8}", MB_8) 
  .replaceText("{mbd_9}", MB_9) 
  .replaceText("{mbd_10}", MB_10)

So, long story short: How can I loop that replaceText part for 300 variables? I've seen solutions with "this." but I couldn't figure how to use it in this context.

Your support is very much appreciated.

CodePudding user response:

Instead of using a variable for each single value, and reading one value at a time, as it's being done in

var MB_1 =  ws.getRange("C1").getValue();

read all the values at once

var MB = ws.getDataRange().getValues();

Note: To get the values as they are formatted in Google Sheets, instead of getValues use getDisplayValues().

then use Array indexes as follows

docBody
  .replaceText("{mbd_1}", MB[0][2]) 

Depending on your spreadsheet structure, you could take it further, i.e. using a loop (assuming that all the values are in Column C), like the following:

MB.forEach((row,i) => docBody.replaceText(`{mbd_${i   1}}`, MB[i][2]))

References

  • Related