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 ?

3
  • You should use Eval for such cases Commented Nov 28, 2016 at 9:14
  • 1
    in the data structure? i suggest to use objects for named parts instead of name variables with a variable part. Commented Nov 28, 2016 at 9:14
  • 3
    Assuming the object is present in the global namespace, window['nameA_' + ccc]['abc'].aaa Commented Nov 28, 2016 at 9:14

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

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

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.