Node dynamic variables

i would like to be able to select a const value using a variable. something like this (below) but without the horrible if/then statement (or a switch/case statement)

    const variableOne    = 'this is variable one';
    const variableTwo    = 'this is variable two';
    const variableThree  = 'this is variable three';
    let testVar = 'variableThree';
    let result;
    if  ( testVar == 'variableOne' ) {
        result = variableOne;
    } else if  testVar == 'variableTwo' ) {
        result = variableTwo;
    } else if testVar == 'variableThree' ) {
        result = variableThree;
   }
    console.log(testVar);

yes an object would work, but i would really like to not have to change all the const values:

 let testVar = 'variableThree';
 let myObj = 
   { variableOne    :  'this is variable one' },
   { variableTwo    : 'this is variable two' },
   { variableThree  : 'this is variable three'};
  console.log(myObj[testVar]);

or even this, but i am still be changing the const statements:

    global['variableOne'] = 'this is variable one';
    global['variableTwo'] = 'this is variable two';
    global['variableThree'] = 'this is variable three';
    let  thisVar = 'variableThree';
    console.log(global[thisVar]);

is there possibly a better way to do this? i cannot think of one. i thought i remembered reading something like this might work, but i forget the syntax.

    const variableOne    = 'this is variable one';
    const variableTwo    = 'this is variable two';
    const variableThree  = 'this is variable three';
    let testVar = 'variableThree';
  
    console.log( ${testVar} );   // this does not work, but hopefully it demonstrates the concept.

ohhh and NO eval() statements - this would create a huge security issue i just assume not have to deal with.

Not that I am aware of. You’ve pretty much summarized the various ways of doing this in your question.

There is eval, but it’s use is not recommended. See Never use Eval()!

const variableOne    = 'this is variable one';
const variableTwo    = 'this is variable two';
const variableThree  = 'this is variable three';

const testVar = 'Three'
console.log(eval(`variable${testVar}`)) // this is variable three

If there are just a few constants that you want to leave as is, couldn’t you assign their values to an object as well? — I know not very dynamic.

const variableOne    = 'this is variable one';
const variableTwo    = 'this is variable two';
const variableThree  = 'this is variable three';

// assign consts to an object?
const options = { variableOne, variableTwo, variableThree}
const testVar = 'Two'
console.log(options[`variable${testVar}`]) // this is variable two
2 Likes

ya but not much fun either… :blush:

its surprising there is not an option like console.log( ``${testVar}`` ); – i should think this would be a useful feature…?

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.