0

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.

Rubén
  • 34,714
  • 9
  • 70
  • 166
  • You can create a lot of properties with an object – Cooper Nov 08 '22 at 17:33
  • Thanks. Not sure where to take that, Cooper. How would I go about taking a value (in this case, PERSON_ID) and dynamically use it, in code, to create a var called PERSON_ID? – Kenton Sparks Nov 08 '22 at 17:37
  • I don't understand precisely what you are trying to accomplish – Cooper Nov 08 '22 at 17:41
  • I begin without a variable and want to dynamically create one with a name found in a column. In this example, I have a column heading called PERSON_ID. What I want to do is retrieve that heading (which is simple) and then use the retrieved name to create a variable with that name. So, I'd be looking for a var called PERSON_ID once the code runs. – Kenton Sparks Nov 08 '22 at 17:43
  • in short, you can't, there is no way you can dynamically name a variable with random string. To accomplish a similar result, we create an Object and set Object keys with dynamical names and the paired value as the value of that so call "dynamical variable". – Ping Nov 08 '22 at 17:45
  • I think I get the idea, but I've never used or set properties of an object. Do you have an example that's similar to this case? – Kenton Sparks Nov 08 '22 at 17:47
  • Just checked it out. So far as I can tell, can easily assign var values within the object var, but not the names of the vars themselves. – Kenton Sparks Nov 08 '22 at 18:09
  • Answer is below. Thank you. Other (but different) solutions appear in the search list. – Kenton Sparks Nov 08 '22 at 18:16

1 Answers1

2

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)
Ping
  • 891
  • 1
  • 2
  • 10