David David - 6 days ago 6
Javascript Question

Write name of array on the go from name + variable

I have such array component which prints out Good.

console.log(nameA_componentA['abc'].aaa);


But now I want to print it out like this

var ccc='componentA';
console.log(nameA_+ccc['abc'].aaa);


But it's not working unfortunately :(
Where is my mistake ?

Answer

Although it's not recommended, you can do this in Javascript without having to use eval(). Since global variables are descendants of the window object, you can access them like this:

var ccc='componentA';
console.log(window['nameA_' + ccc]['abc'].aaa);

But it's probably better practice to use objects / arrays instead of using this method.

Comments