0

I've got a series of JavaScript objects and a function to tie them together as a questionnaire.

If I call the function directly from the code like setQuestion(Q1), it works fine;

function setQuestion(Q) {
     console.log(Q);          \\ Logs the Q1 object
     console.log(Q.answers);  \\ Logs the Q1.answers object
     console.log(Q2.answers); \\ Logs the Q2.answers object
}

But the variable Q is based upon a dynamically created attribute followup on a input field, for instance;

<input type="radio" name="Q1" followup="Q2" value="A2" id="A2">

But when I use that attribute to call the setQuestion function, it doesn't recognize the object;

var followup = this.getAttribute('followup');
setQuestion(followup);

Say that followup is Q2;

function setQuestion(Q) {
     console.log(Q);          \\ Logs `Q2` as text
     console.log(Q.answers);  \\ Logs `undefined`
     console.log(Q2.answers); \\ Logs the Q2.answers object
}

It's clear that the function sees the attribute value as a textvalue, and thus doesn't get the object, so how can I make it see the attribute value variable as the related object?

FYI: the objects are defined like this;

var Q1 = { ... };
var Q2 = { ... };
etc.
Asitis
  • 382
  • 3
  • 17
  • 1
    Use an object indexed by Qs instead, eg `const allQs = { Q1: { answers: ... }, Q2: { ...` and then you can just use bracket notation to look up the proper object on `allQs` – CertainPerformance Aug 14 '19 at 08:56
  • @CertainPerformance; that works while maintaining the flexibility I need! If you'd like, post this as an answer I'll accept it! – Asitis Aug 14 '19 at 09:25

1 Answers1

0

You could move the questions into a questionaire and use the handed over values as key.

var Q1 = { ... },
    Q2 = { ... },
    questionaire = { Q1, Q2, ...};
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392