I'd like to use a variable that contains the key value for a hash table in Google Apps Script.
In place of:
var folderRoots = {
"EYFS English":"sdfg0987897sdfga3",
"EYFS Italian":"sdf8f9g7897sfdfg7",
}
var b = folderRoots["EYFS English"]; // gets sdfg0987897sdfga3
I would like to use:
var depEYFSEn = "EYFS English";
var depEYFSIt = "EYFS Italian";
var folderRoots = {
[depEYFSEn]:"sdfg0987897sdfga3",
[depEYFSIt]:"sdf8f9g7897sfdfg7",
}
var b = folderRoots[depEYFSEn]; // gets sdfg0987897sdfga3
However, when attempting to use square brackets for the key variable as suggested here, the editor will throw an error
Invalid property ID
Maybe Google Apps Script Javascript implementation does not support this?
Unfortunately, computed property names are a feature in ES6, and Google Apps Script is still at ES5.
Instead, you can create your keys from your variables by setting the key on the object using bracket notation []
:
var depEYFSEn = "EYFS English";
var depEYFSIt = "EYFS Italian";
var folderRoots = {};
folderRoots[depEYFSEn] = "sdfg0987897sdfga3";
folderRoots[depEYFSIt] = "sdf8f9g7897sfdfg7";
var b = folderRoots[depEYFSEn]; // gets sdfg0987897sdfga3
console.log(b);