1

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.

newneub
  • 183
  • 1
  • 14
  • It would be a lot easier if you could be getting properties instead of the entire object, then it's just `obj["object_" + questionId]` – adeneo Mar 22 '16 at 19:54
  • If you think you need to use dynamic variables, you're probably doing something wrong. You should put all the objects into an array, and then use `questions[questionId]`. – Barmar Mar 22 '16 at 20:07

3 Answers3

1

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}

shershen
  • 9,875
  • 11
  • 39
  • 60
  • Or just store the questionId as a key in the object without the superfluous prefix :) – Andy Mar 22 '16 at 20:08
1

Short answer: global scope + brackets.

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

Long answer: Use dynamic variable names in JavaScript

Community
  • 1
  • 1
0

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392