David
David

Reputation: 4518

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 ?

Upvotes: 2

Views: 84

Answers (3)

Luuuud
Luuuud

Reputation: 4439

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.

Upvotes: 4

Rajesh
Rajesh

Reputation: 24955

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

Upvotes: 0

synthet1c
synthet1c

Reputation: 6282

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)

Upvotes: 0

Related Questions