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'];
Tomas Am
  • 433
  • 4
  • 13

2 Answers2

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);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
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 // ...
Dennis Hackethal
  • 13,662
  • 12
  • 66
  • 115