'Reference JS object through concatenation

I am trying to call an object.

The way I am currently doing it:

var key = object_0

The way I'd like to do it

var key = "object_" + questionId;

But when calling the concatenated object_0 I do not get the object info when I do a:

console.log(key)

Any insight would be awesome.



Solution 1:[1]

Short answer: global scope + brackets.

window['object_'+questionId] = 'foo';
console.log(window['object_'+questionId]); // 'foo'

Long answer: Use dynamic variable names in JavaScript

Solution 2:[2]

If you use ES5 you can do so with creating new empty object. Here are the steps:

1.create empty object

var o = {};

2. use brackets to produce the new key on an object - ("object_" + questionId) - this will force the parser first to evaluate expression in the brackets

3.assign value to a newly added key

o[("object_" + questionId)]  = XXX;

Then console.log(o) will output {object_0: XXX}

Solution 3:[3]

You can use the window object (access to global variables only):

var object_0 = { p: 42 },
    questionId = 0,
    key = "object_" + questionId;
document.write(window[key].p);

But i suggest to change the data structure to a more concise style:

var questions = { 200: { p: 42 }},
    questionId = 200;
document.write(questions[questionId].p);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2 shershen
Solution 3 Nina Scholz