Search code examples
javascripthtmlarraysdictionarygetelementbyid

How to make two arrays into a single key-value pair dictionary to pass to HTML from JS


I am making a program in which the user presses a button to get a random question and then can press another button to get the answer. I wanted to make a dictionary in JS to contain the questions and answers but couldn't figure out how to do so, so I opted for two arrays; one with the questions and one with the answers. This method works fine but I know there must be a more correct way to accomplish the same thing with a dictionary containing key-value pairs. Here is the JavaScript code:

const questions = Array(
"Question one",
"Question two",
"Question three",
);

const answers = Array(
"Answer one",
"Answer two",
"Answer three",
);

function randomQuestion() {
  const len = answers.length;
  const rnd = Math.floor(Math.random() * len);
  document.getElementById('randomQuestion').value = questions[rnd];
  document.getElementById('randomAnswer').value = answers[rnd];
}

Thank you in advance. I am new to coding so any help is appreciated!


Solution

  • Melih's answer is correct but without using classes just do this:

    const questions = [
    { question: "Question one", answer: "Answer one" },
    { question: "Question two", answer: "Answer two" },
    { question: "Question three", answer: "Answer three" },
    ];
    
    function randomQuestion() {
      const len = questions.length;
      const rnd = Math.floor(Math.random() * len);
      document.getElementById('randomQuestion').value = questions[rnd].question;
      document.getElementById('randomAnswer').value = questions[rnd].answer;
    }