Search code examples
javascriptobjectconcatenation

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

  • Short answer: global scope + brackets.

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

    Long answer: Use dynamic variable names in JavaScript