0
// declared read-only variable:
const support = {
        arr: {
            ins: ['g3', 'g5', 'g7', 'g10',
                'g12', 'g13', 'g14', 'g15'
            ]
        }
    },
// object destructuring for easy to call:
{ arr: { ins: supE1range } } = support;

and a function to dynamically change between sup and 1 in supE1range object:

function autoSelect(currClass, currElite) {
    let setClass = '';
    switch (currClass) {
        case 'support':
            setClass = 'sup';
            break;
    }
    let setObj = `${setClass}E${currElite}range`;
    console.log(eval(setObj));
}
autoSelect('support', 1);

as you can see eval(setObj) will get supE1range's value because the string is match to the object name.

and now how to accomplish that without eval?
I've searching related questions/answers but doesn't satisfy want i need.
umm.. don't mind about 'dynamically change' because it's just part of the code that is unnecessary to put here

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Musadarj
  • 62
  • 3
  • 9
  • like this? https://stackoverflow.com/questions/6865537/executing-a-string-without-eval-or-is-eval-ok-to-use-here – Thomas Feb 04 '22 at 07:02

1 Answers1

3

My suggestion is instead of creating a variable from destructuring, try creating an object (map in this case) to hold the value with keys you specify.

Then retrive the value by looking up map object.

const map = {};

// declared read-only variable:
const support = {
    arr: { ins: map.supE1range = ['g3', 'g5', 'g7', 'g10', 'g12', 'g13', 'g14', 'g15'] },
};

function autoSelect(currClass, currElite) {
    let setClass = '';
    switch (currClass) {
        case 'support':
            setClass = 'sup';
            break;
    }
    let setObj = `${setClass}E${currElite}range`;
    console.log(map[setObj]);
}
autoSelect('support', 1);

Or you could declare the variable using var and then retrive the value using window object(not recommended)

// declared read-only variable:
var support = {
        arr: {
            ins: ['g3', 'g5', 'g7', 'g10',
                'g12', 'g13', 'g14', 'g15'
            ]
        }
    },
// object destructuring for easy to call:
{ arr: { ins: supE1range } } = support;

function autoSelect(currClass, currElite) {
    let setClass = '';
    switch (currClass) {
        case 'support':
            setClass = 'sup';
            break;
    }
    let setObj = `${setClass}E${currElite}range`;
    console.log(window[setObj]);
}
autoSelect('support', 1);
Hao Wu
  • 17,573
  • 6
  • 28
  • 60