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.

2
  • It would be a lot easier if you could be getting properties instead of the entire object, then it's just obj["object_" + questionId] Commented Mar 22, 2016 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]. Commented Mar 22, 2016 at 20:07

3 Answers 3

1

Short answer: global scope + brackets.

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

Long answer: Use dynamic variable names in JavaScript

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

1 Comment

Thank you for the short and long answer.
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}

1 Comment

Or just store the questionId as a key in the object without the superfluous prefix :)
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);

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.