1

Say I have these JavaScript objects:

questions = { name: "Age", options:[boy, girl, daddy]}
answers = {"Age" : 21, "boy" : "checked", daddy : "checked"}

So if I wanted to access the "Age" from the answers object, I would do:

x = answers.Age   //21

But how can I do the same thing but instead using the values from the questions object?

x = answers.questions.name   //problem

or

answers.questions.options[0]  //problem

As you can see I am trying to use the value of questions.name ("Age") to access a property of answers (Age).

What's the right syntax or way?

2 Answers 2

4

Try this:

var x = answers[questions.name]

This works because:

answers.Age

is equivalent to:

answers['Age']
Sign up to request clarification or add additional context in comments.

Comments

3

Use indirect referencing

answers[questions.name]

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.