2

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 ?

David
  • 4,332
  • 13
  • 54
  • 93

3 Answers3

4

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.

Luuuud
  • 4,206
  • 2
  • 25
  • 34
0

You can use eval for such cases.

var nameA_componentA = {
  abc: {
    aaa: 'Hello World'
  }
}

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

Note: If you have option to restructure your code to wrap all such objects inside a wrapper object, you should do it. Consider eval as last resort.

var nameA_componentA = {
  abc: {
    aaa: 'Hello World'
  }
}
var nameA_componentB = {
  abc: {
    aaa: 'Hello Foo'
  }
}

var wrapperObj = {
  nameA_componentA: nameA_componentA,
  nameA_componentB: nameA_componentB
}

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

References

Community
  • 1
  • 1
Rajesh
  • 24,354
  • 5
  • 48
  • 79
0

you could use (window || context)['nameA_' + ccc].abc.aaa

const nameA_componentA = {
  abc: {
    aaa: 'Good'
  }
}
console.log(nameA_componentA['abc'].aaa);
const ccc='componentA';
// this isn't working in the stack snippets
// console.log(window['nameA_' + ccc]['abc'].aaa);

// you are better off namespacing
const nameA = {
  componentA: { abc: { aaa: 'Good' }},
  componentB: { abc: { aaa: 'Great' }}
}

console.log(nameA[ccc].abc.aaa)
synthet1c
  • 6,152
  • 2
  • 24
  • 39