2

I am trying to figure out the best way to dynamically build variables. I have a database that looks like this:

One record:

ans1
ans2
ans3

res1
res2
res3

I have a function that checks the answer against the button the user pressed.

checkAnswer(q, a, $event) {
    if(a == q.correct){
        this.correctanswer = q.success
    }
}

The variable 'a' is either 1, 2 or 3

I would like the code to look something like this:

this.correctanswer = q.res+a

However, this is not working. How can I look up the appropriate response based on the answer the user chooses? So if the user presses answer 1 they see res1 and so on.

7
  • what does q look like?
    – charlietfl
    Commented Feb 10, 2019 at 22:40
  • it doesn't what that needs to end up being is q.res1 if the user chose answer 1
    – Jason
    Commented Feb 10, 2019 at 22:40
  • 1
    this is in reference to what? Please show a little more code. I think its probably something real simple. Commented Feb 10, 2019 at 22:41
  • we can ignore this for now as it is not necessary for my request
    – Jason
    Commented Feb 10, 2019 at 22:42
  • 1
    Use [] notation for variable property names.... q['res'+a]
    – charlietfl
    Commented Feb 10, 2019 at 22:42

1 Answer 1

3

Use [] (square bracket notation):

this.correctanswer = q["res" + a];
4
  • res should be string
    – charlietfl
    Commented Feb 10, 2019 at 22:44
  • Sorry @charlietfl, fixed now. Commented Feb 10, 2019 at 22:45
  • You were correct. I can't believe I completely forgot about square bracket notation. thank you
    – Jason
    Commented Feb 10, 2019 at 22:50
  • Yes, I was waiting for Stackoverflow to allow me :)
    – Jason
    Commented Feb 10, 2019 at 23:13

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.