Search code examples
javascriptarraysfor-in-loop

Calling array element with index from an array inside the array JavaScript


I want to make a survey app in JS and I have a the following code in the main:

for(var questionNumber in questionsAndAnswers.allQuestions){
      for(var i in questionsAndAnswers.allQuestions[questionNumber]){
        console.log(questionsAndAnswers.allQuestions[questionNumber].question);
        console.log(questionsAndAnswers[questionNumber+1]);
    } 
}

And this code in the config:

const questionsAndAnswers = {
    "allQuestions": [
        { "question": "Write your first question here",
        },
        { "question": "Write your second question here",
        },
        { "question": "Write your third question here",
      }
     ],
    "answerOne": [
        "1.This is the first answer",
        "1.This is the second answer",
        "1.This is the third answer"
        ],
    "answerTwo": [
        "2.This is the first answer",
        "2.This is the second answer",
        "2.This is the third answer"
      ],
     "answerThree": [
        "3.This is the first answer",
        "3.This is the second answer",
        "3.This is the third answer"
      ]
}

And then this comes out:

Write your first question here
undefined
Write your second question here
undefined
Write your third question here
undefined

I want to do this: when the first question is asked, only the first answers to appear, but when I call console.log(questionsAndAnswers[questionNumber+1]);Undefined appears. I tried many options, but the main problem is separating the questions from answers and dinamically adding a question + answer, when the config is changed, without changing the main. I would be very greatfull, if you could help me.

Thanks!


Solution

  • I used what Tushar said:

    I suggest to store the question & answers in same object. { question: "abc", answers: ["abc", "def", ghi"], correct: 0}.

    Thanks