1

I have many objects (global):

let JohnA = {some data};
let GeorgeA = {some data};
...

Now I want to select an object by it's name in this context:

....
var randomselected = "John";
var result = obj.countries[key]['dataform'];
....

Here instead of obj. I need to have something like:

var result = randomselected+"A".countries[key]['dataform'];

So it works same as with:

var result = JohnA.countries[key]['dataform'];
1

2 Answers 2

1

JavaScript won't give you a list of declared variables and their names, so what you're trying to do won't work with plain variables unless you use eval like in Majed's answer, but I don't recommend that—using eval is generally discouraged because depending on your code it can open you up to security vulnerabilities.

What you could do instead is store JohnA and GeorgeA as properties on an object like so:

let names = {
  JohnA: { countries: ... },
  GeorgeA: { countries: ... } 
}

and then you can programmatically access those properties:

let name = 'John';
names[name + 'A'].countries // ...
Sign up to request clarification or add additional context in comments.

1 Comment

1

You can use eval. Here is a simple example:

let JohnA = {name:"John"};
let p = "John";
let name = eval(`${p}A`).name;
console.log(name);

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.