1

For example I want to extract an object array from an Enum definition.

Object.keys(HelloWorldEnum).map(el => {
  return {
    label: HelloWorldEnum[el],
    value: el
  };
});


enum HelloWorldEnum {
  option1 = 'Option1',
  option2 = 'Option2',
  option3 = 'Option3'
}

Now, how I can do with a function that passing 'HelloWorld' as a variable, below is not work:

getOptions(str) {
    return Object.keys([str + 'Enum']).map(el => {
      return {
        label: [str + 'Enum'][el],
        value: el
      };
    });
  }

Even I changed to window[str + 'Enum'], or this[str + 'Enum'] that it won't works since the Enum definition is not existing in neither window nor this namespace

Assume the above code is in any of an Angular Component

Vincent
  • 1,178
  • 1
  • 12
  • 25
  • is enum a requirement? there are much better ways to solve this? – jcuypers Mar 19 '19 at 23:21
  • Possible duplicate of [How to get local variable by its name in JS?](https://stackoverflow.com/questions/2146173/how-to-get-local-variable-by-its-name-in-js). – jcalz Mar 20 '19 at 00:28
  • The short answer here is that you shouldn't try to access a variable via a string representing its name. Instead you should maintain a mapping of string names to variable contents, also known as an object... e.g., `const enums = {HelloWorld: HelloWorldEnum};` and then `enums[str]`. – jcalz Mar 20 '19 at 00:31

1 Answers1

0

Typescript will ultimately transpile your enum definition to something that looks like:

var HelloWorldEnum = {};
HelloWorldEnum["option1"] = "Option1";
HelloWorldEnum["option2"] = "Option2";
HelloWorldEnum["option3"] = "Option3";

As you can see. It's just a variable name in local scope. It's not added to the global window object or any other object.

There is only one way to access a variable by it's name in javascript and it's not recommended... and that's by using eval() which is considered a dangerous api which can cause performance issues in your javascript engine just by using it.

Warnings aside. Here is how one might do what you ask.

var HelloWorldEnum = {};
HelloWorldEnum["option1"] = "Option1";
HelloWorldEnum["option2"] = "Option2";
HelloWorldEnum["option3"] = "Option3";

function getVariableFromScope(variable) { return eval(variable); }
function getOptions(name) {
  const _enum = getVariableFromScope(`${name}Enum`);
  return Object.keys(_enum).map(el => ({ label: _enum[el], value: el }));
};
console.log(getOptions('HelloWorld'));

Ultimately, I think you should explore other ways of solving the underlying issue.

Doug Coburn
  • 2,485
  • 27
  • 24