1

I'm making a Trivia game and have an object full of questions and answers. I want to display the first question and the choices users have on the screen. After they guess, the program displays the second question.

This is what I have so far:

var qAndA = {
  q1: {
    question: "What is the capital of nevada",
    choices:["Reno","Carson City","Las Vegas", "Boulder City"]
  },
  q2:{
    question: "What is the capital of Oregon?",
    choices:["Salem","Portland","Eugene","Bend"]
  },
  q3:{
    question: "What is the capital of Vermont?",
    choices:["Burlington","Bennington","Stowe","Montpelier"]
  },
};

function questionsAnswers(){
  timer();
  //This Is Where I want To Use A Loop Rather Than Writing Out ".q1.question"
  $("#main").append(qAndA.q1.question);
}

Is there a way to target a specific object in the array without having to write qAndA.q1.question so I don't have to write it out for each individual question (Perhaps some sort of loop to do this)?

2 Answers 2

1

Keys in objects can also be referenced using the array notation, which treats the key name as plain strings:

var myObj = {
    key1: 'a',
    key2: 'b',
    key3: 'c'
}


console.log(myObj.key1) // 'a'
console.log(myObj["key1"]) // 'a'
console.log(myObj["key" + "1"]) // 'a'
Sign up to request clarification or add additional context in comments.

Comments

0

Try re-writing qAndA.q1.question as qAndA.["q"+i].question as dynamic as possible. You can assign "q"+i to a var and append it to the above expression. This expression shall be in a loop :

var size = Object.keys(qAndA).length;

for (var i=1;i<=size ;i++){
  var c= "q"+i; //q1 when i=1 and so on
  // do ur routine stuff
  //qAndA["q"+i] === qAndA[c]
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.