0

I'm new to Javascript - I tried searching the web was not able this situation into context.

Here is the situation:

import * as People from ./People.json
import * as Education from ./Education.json
import * as Vehicle from ./Vehicle.json
...
function transpose(str : string) {
  let data = {};
  if(validate(str))  //validate function returns true if valid string
    data = str  //data takes in the string value and uses variable name
    runFile(data); //runFile expects data to be a JSON type
  ...
}

Essentially how do I convert str (string variable into a variable) if suppose str = "People" then data will be equal to the variable People or if str = "Vehicle" data will be Vehicle variable.

I know this can be done with a map of {"People": People, "Vehicle": Vehicle} it just seems like there should be a better way? I also looked into eval(str) but that doesn't seem to do the trick.

Any help would be appreciated.

Thanks

3
  • 1
    Only good way I see is to use an object and bracket notation. Eval almost never is a good idea. Commented Jul 10, 2018 at 0:47
  • @Li357 so you mean data = [str] ? Commented Jul 10, 2018 at 1:08
  • No, what mpen answered Commented Jul 10, 2018 at 1:13

2 Answers 2

3

A "map" really is the best way. Good news is that you can save a few keystrokes with shorthand property names (ES2015):

import * as People from ./People.json
import * as Education from ./Education.json
import * as Vehicle from ./Vehicle.json

const lookup = {People,Education,Vehicle}; // equivalent to {"People":People, ...}

function transpose(str : string) {
  let data = {};
  if(validate(str))  //validate function returns true if valid string
    data = lookup[str]  //data takes in the string value and uses variable name
    runFile(data); //runFile expects data to be a JSON type
  ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Ahh i was hoping this wouldn't be the solution.. thanks a lot @mpen +the pointer on ES2015
-1

Useful if you want to pass in JSON as a parameter to the transpose function.

function transpose(jsonObj, str) {
  let data = {};
  if(validate(str))
  {
    data = jsonObj[str];
    runFile(data); //runFile expects data to be a JSON type
  }
  ...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.