-1

I have some data in a class that is imported to be used when a variable name is the same as the imported class name. I don't know the best way to first check the value if its the same as the imported class name.

Right now my code looks like:

import { TEST, TEST2 } from '../shared/panel';

selectPanel(panel) {
  let test;
  if(panel === 'TEST'){
    test = TEST;
  }   
  else if(panel === 'TEST2'){
    test = TEST2;
  }
  else{
    test = '';
  }
}

Is there any shorter way or better way to do this? Cause when there are lots of condition it become messy.

user3794740
  • 312
  • 1
  • 7
  • 18
  • 2
    use a switch statement – Derek Pollard Apr 11 '19 at 15:40
  • @DerekPollard hmm, not really what I expected. since the value of the class name and the value to be compared is the same, is there any way to write it better way? – user3794740 Apr 11 '19 at 15:41
  • `'TEST' and TEST` aren't the same though; One is a value and the other is a variable name – Derek Pollard Apr 11 '19 at 15:42
  • possible duplicate: https://stackoverflow.com/questions/5613834/convert-string-to-variable-name-in-javascript – Pete Apr 11 '19 at 15:42
  • if your vars aren't in the global namespace, you better read this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval before going the eval route – Pete Apr 11 '19 at 15:52
  • @DerekPollard its is the same in terms of the names, which is answered by El Aoutar Hamza below – user3794740 Apr 11 '19 at 17:12

2 Answers2

2

You can import all the variables this way:

import * as panels from '../shared/panel';

Now you will have an object (panels) that has your variables names as keys.

So you can do something like:

const selectPanel = key => panels[key] || ""
Hamza El Aoutar
  • 5,292
  • 2
  • 17
  • 23
0

try this

selectPanel(panel) {
  let test;
  if(window[panel]=="undefined"){
    test = '';
  }
  else{
  test = window[panel]
  }
}

I didn't test but i think it will work