Search code examples
javascriptgoogle-apps-scriptdynamic-variables

Create variable names dynamically based on column headings


Suppose a google sheet column name, PERSON_ID, retrieved by code.

How can I dynamically create a variable with this name? I'm envisioning something like this:

var columnName='PERSON_ID';

var [columnName]=''

Hopefully, the idea is clear.


Solution

  • Here is an example to accomplish what I believe you are trying to do:

    const variables = {}; // create an empty object and name it "variables".
    const ranStr_1 = "ABC";
    const ranStr_2 = "XYZ";
    
    // set the string "ABC" and "XYZ" stored in variable 'ranSTR_1' and 'ranSTR_2' as keys inside the Object 'variables', with paired values "value 1" and "value 2".
    variables[ranStr_1] = "value 1"; 
    variables[ranStr_2] = "value 2";
    
    console.log(variables.ABC) // should shows "value 1" in console.
    console.log(variables["ABC"]) // should shows "value 1" in console.
    console.log(variables.XYZ) // should shows "value 2" in console.
    console.log(variables["XYZ"]) // should shows "value 2" in console.
    
    // you can also do something like this:
    
    const varNames = ["name_1","name_2","name_3","name_4"];
    
    for (const [i,key] of varNames.entries()) {
      variables[key] = i
    }
    
    // shows all stored key: value pairs in console:
    console.log(variables)