Home > Software engineering >  How do I get my for loop to go through my array of objects?
How do I get my for loop to go through my array of objects?

Time:05-22

I've created an array of objects that I need my for loop to go through. However, when I run this code, I only ever seen the first question and its answers. What am I doing wrong? Thank you in advance!

// An array of objects containing questions, answers, and the correct answers.
const questionArray = [
    {
        Q: "TestingQ1",
        A: [
            "Testing2",
            "Testing3",
            "Testing4",
            "Testing5"
        ],
        Correct: "Testing2"
    },
    {
        Q: "TestingQ2",
        A: [
            "Testing2-2",
            "Testing3-2",
            "Testing4-2",
            "Testing5-2"
        ],
        Correct: "Testing3-2"
    }

];

// Set to zero to target the first index in an array of objects.
let questionIndex = 0;
// showQuestions is equal to elements with the "show-questions" class.  Here, a section.
let showQuestions = document.querySelector(".show-questions");
// showAnswers is equal to the elements in the "show-answers" class.  Here, a section.
let showAnswers = document.querySelector(".show-answers");
// results is equal to the "results" id.  Here, a span.
let results = document.querySelector("#results");

// Create a function that displays questions
function displayQuestions() {
    showQuestions.textContent = questionArray[questionIndex].Q;
    console.log(showAnswers);
    for (let i = 0; i < questionArray[questionIndex].A.length; i  ) {
        let answerButton = document.createElement("button");
        answerButton.textContent = questionArray[questionIndex].A[i];
        // Define the function here to check the answers
        answerButton.onclick = function checkAnswers() {
            // If the submission is equal to Correct...
            if (answerButton.innerText === questionArray[questionIndex].Correct) {
                // ...show this confirmation message.
                results.textContent = "Right on, popcorn! That's correct.";
                console.log(checkAnswers);
                // If the submission is not equal to Correct...
            } else {
                // ...show this error message and...
                results.textContent = "Sorry, no such luck. Try again!";
                // ...deduct 10 seconds from the clock.
                secondsLeft -= 10;
            }
        };
        showAnswers.appendChild(answerButton);
    }

CodePudding user response:

Check my git repo same application , and check the quiz.js file

I also attached the quiz.js code here

repo link: https://github.com/abdulhaseeb036/quiz-website

quiz.js code:

var questions = [
    {
        id : 1,
        question : "Who is the owner of this Quiz app",
        answer : "Haseeb Alam Rafiq",
        option : [
            "Haseeb Alam Rafiq",
            "Muhammad Wasi",
            "Mark zinger Burger",
            "None of these"

        ]
    },

    {
        id : 2,
        question : "When was MR HASEEB ALAM born?",
        answer : "12-dec-2000",
        option : [
            "13-aug-2000",
            "12-may-1999",
            "1-march-2001",
            "12-dec-2000"

        ]
    },

    {
        id : 3,
        question : "Which university MR HASEEB ALAM RAFIQ complete Becholars degree?",
        answer : "Lumber 1 university",
        option : [
            "Baharia university ",
            "Lumber 1 university",
            "IBM university",
            "DHA suffah university"

        ]
    },   
]



// var welcome = document.getElementById(location.href="../index.html" ,"first-ip");
// console.log(welcome.value);

// counter
var counter = 0;
var userPoints = 0;
function nextq() {

    var userAns = document.querySelector("li.option.active").innerHTML;
    if (userAns == questions[counter].answer){
        userPoints = userPoints   5;
        sessionStorage.setItem("points" ,userPoints);

    }

    if (counter == questions.length -1) {
        location.href = "../end.html";
        return;    
    }

    console.log(userPoints);
    counter  ;
    show(counter);

}

// on every onl oad mean refresh this function calls and in this function
// show(counter) function calls
window.onload = function() { 
    show(counter); //here counter value 0 means first q render on refresh page.
}


// this function render onclick new question with options 
function show(counter) {
    var question = document.getElementById("questions");
    question.innerHTML=`
    <h2>Q${counter  1}. ${questions[counter].question}</h2>
    <ul>
    <li >${questions[counter].option[0]}</li>
    <li >${questions[counter].option[1]}</li>
    <li >${questions[counter].option[2]}</li>
    <li >${questions[counter].option[3]}</li>
    </ul>
    `;
    toggleActive();
}



function toggleActive() {
          let option1 = document.querySelectorAll("li.option");

for(let i = 0; i< option1.length; i  ){               
    option1[i].onclick =function() {                 
     for(let j = 0; j< option1.length; j  ){       
        if(option1[j].classList.contains("active")){  
            option1[j].classList.remove("active");  
        }
        option1[i].classList.add("active");

      }
    }
    
  }
}

CodePudding user response:

You're not seeing a loop through your other questions because your for loop is bound to your first object.

for (let i = 0; i < questionArray[questionIndex].A.length; i  )

This means that your for loop should end with the length of the answers in your first object. After this your loop should close. To get your loop to go through all objects you can go through two ways per my knowledge: My preferred way

A forEach loop on your array and then the for loop for each object as your have done.

Or

You can probably create a first forLoop for your array objects before the inner forLoop which you you have.

This way, there is a loop going through your questions and a loop to find your answer.

I hope this guides you on how to go about it.

  • Related