Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

137
Views
Display API Response into an array

I'm making a Trivia Game and I'm using The Open Trivia Database to generate 10 random questions.

These 10 questions are separate strings and I want to place them into an array so that I can display them one by one (after the user guesses whether it's True or False.)

Here is the console log of the questions:

enter image description here

Now here is what I'm trying: I have initialized an empty array and then, in the for loop, I'm pushing each question into the array but its not working.

Essentially, what I'm trying to achieve is that when the user clicks a true or false button, the next item in the response will be displayed. I thought an array would work but maybe I'm looking at it in the wrong way.

Any help is appreciated and if I missed something, please let me know. Thank you in advance!

Code:

const api_url =
  "https://opentdb.com/api.php?amount=10&difficulty=easy&type=boolean";
const triviaQ = document.getElementById("triviaQuestion");
const question_array = []; // this is the empty array

async function getAPI(url) {
  const response = await fetch(url);

  var data = await response.json();

  justQuestions(data);
}

function justQuestions(data) {
  /// loop to display all 10 questions
  for (let i = 0; i <= 9; i++) {
    display_all_questions = data.results[i].question;
    current_question = triviaQ.innerHTML = display_all_questions; /// the console log image
    let all_questions = question_array.push({ display_all_questions }); //this is where I attempt to add the questions into an array
  }
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

First, you are creating a variable 'all_questions' on each iteration and never use it (you don't need it). Second, 'display_all_questions' name is misleading, as it is just the current question.

And finally, your data.results is already the array that you need, so you can just use it like this:

let questions_array = [];

async function getAPI(url) {
  const response = await fetch(url);

  var data = await response.json();

  questions_array = data.results;
  console.log(questions_array);
}

Don't forget to handle possible network request errors

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!