Getting the key and value of an object in javascript via ‘for in’

I am beginning a exercise to create a quiz in javascript. Anyway, I have an array which contains the questions; each question is a anonymous object…

var allQuestions = [{
"question": "Who was Luke's wingman in the battle at Hoth?",
"choices": ["Dak", "Biggs", "Wedge", "fx-7"],
"correctAnswer": 0},
{
"question": "What is the registry of the Starship Reliant?",
"choices": [ "NX-01", "NCC-1864", "NCC-1701", "NCC-2000"],
"correctAnswer": 1}...etc.

At this point i’d like to simply iterate through them and insert them into the DOM.

var output = '';

for (key in allQuestions[0]) {
        output += '<li>' + allQuestions[0] + '</li>';
    }

 var update = document.getElementById("question");

 update.innerHTML = output;

But all I get is:

[object Object]
[object Object]
[object Object]

At some point i’d like to match or have ‘question’, ‘choices’ flow in to corresponding elements on the page….

<h2>question</h2> //question from object
<ul id="question">
 <li>choice</li> //choice from object
 <li>choice</li>
 <li>choice</li>
 <li>choice</li>

Answer

You’re using allQuestions[0] inside the loop, but you probably meant to refer to key:

for (key in allQuestions[0]) {
    output += '<li>' + key + '</li>';
}

However, this will return question, choices, correctAnswer. If the items in allQuestions are in the same format you’re better off looping over them and referring to the relevant properties:

for (var i = 0; i < allQuestions.length; i++) { 
  var item = allQuestions[i];
  console.log(item.question);
  console.log(item.choices);
  // etc. 
}

Leave a Reply

Your email address will not be published. Required fields are marked *