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

Time:07-16

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!

CodePudding user response:

class QuestionAnswer {
  QA;
  constructor() {
    this.QA = [];
  }

  AddQuestion(question, answer) {
    this.QA.push({ question: question, answer: answer });
  }

  GetQuestion(index) {
    return this.QA[index];
  }
}

const qa = new QuestionAnswer();
qa.AddQuestion("Q1", "A1");
qa.AddQuestion("Q2", "A2");
qa.AddQuestion("Q3", "A3");

const q1 = qa.GetQuestion(1);
console.log(`Question: ${q1.question} - Answer: ${q1.answer}`);

CodePudding user response:

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 = answers.length;
  const rnd = Math.floor(Math.random() * len);
  document.getElementById('randomQuestion').value = questions[rnd].question;
  document.getElementById('randomAnswer').value = questions[rnd].answer;
}
  • Related