Exploring object key-value pairs using the 'for in' loop in JavaScript

Embarking on a project to develop a quiz in javascript, I am starting with an array that holds the questions as anonymous objects.

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.

My goal now is to iterate through these questions and display them in the DOM.

var output = '';

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

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

 update.innerHTML = output;

However, when I try this, I only see:

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

Eventually, I aim to sync up 'question' and 'choices' to populate corresponding elements on the page like so:

<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 №1

Instead of using allQuestions[0] within the loop, consider referencing key:

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

However, using this will result in question, choices, and correctAnswer. If the elements in allQuestions are structured similarly, it's recommended to iterate over them and access the corresponding properties:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create HTML content from a file retrieved from the server

I have been working on a dynamic website project, diving into web development from scratch despite having coding experience in general. As I navigate Angular CLI and Bootstrap, I've come across a fundamental question: Do modern websites house all thei ...

Getting some clarity on how to structure a project using Node.js, Express.js, and React.js

I am in the process of developing a website for online shopping purposes, essentially an e-commerce platform. However, I am facing a dilemma where create-react-app sets up its own Node.js server to communicate with my backend (which handles MySQL queries) ...

The Javascript document refuses to load

I am currently working on a website with the main file named index.html: <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>Title</title> </head> ...

Interactions with API endpoints: requests and corresponding responses

I'm curious to know if it's possible for an HTTP client in Go to send a specific JSON object via POST and have the server respond with a different JSON object. For example, when a client sends the JSON object below: Request Body { "nfNssaiAva ...

Verify the dates in various formats

I need to create a function that compares two different models. One model is from the initial state of a form, retrieved from a backend service as a date object. The other model is after conversion in the front end. function findDateDifferences(obj1, ...

The vertical scroll position of a container with overflowing content does not correspond to the height of its elements

I have a div that has a fixed height of 155px and is set to scroll vertically when overflow occurs. Inside this div, there is an unordered list with a height of 338px. I am attempting to determine when a user reaches the bottom of that div. $('.myD ...

Exploring the advanced features of OpenOffice Draw for improved geometry analysis

Struggling with the draw:enhanced-geometry section that involves draw:enhanced-path and draw:equation. I'm working on an OOo converter but can't seem to find any concrete solutions or extensive documentation about this part. Any suggestions on ho ...

How to Show a GIF in ASP.NET Core 3.0 When OnPost() is Invoked

I'm struggling to incorporate a GIF into my website, and after researching different sources, I've discovered that I need to utilize some Ajax and Javascript. However, I lack experience with both of these technologies. Is there anyone who could p ...

In a React TypeScript application, prevent users from clicking on buttons that represent the same number of answers in a multiple choice question

I'm currently developing a multiple choice component with various properties like the number of options, number of answers, and a callback function to capture user-selected data. Additionally, this component should display a checkmark when a button is ...

Angular 2 System.config map leading to a 404 error message

I am encountering a 404 error in the browser console while attempting to map the Auth0 module from node_modules in my Angular 2 project using the system.config in the index file. Index File <!-- 2. Configure SystemJS --> <script> System.con ...

Building a custom DSL expression parser and rule engine

In the process of developing an app, I have included a unique feature that involves embedding expressions/rules within a configuration yaml file. For instance, users will be able to reference a variable defined in the yaml file using ${variables.name == &a ...

Using res.send() updated the content of the sub-object within my object

This situation is quite unusual. When I send an object from my express server to the frontend, the object is logged in the console as follows: https://i.sstatic.net/gfPe0.png Whether I try to JSON.stringify(wellObj) before sending it or simply use res.sen ...

Appending or removing a row in the P-Table will result in updates to the JSON

My task involves implementing CRUD (Create, Read, Update, Delete) functionality for my table. While Create, Read, and Update are working fine with the JSON file, I am struggling to figure out how to delete a specific row in the table without using JQuery o ...

Revamp the state within a React component

I created a component that organizes logos within a grid system. The component receives 2 props: grid (which contains the logos) and limit (indicating the number of logos to be displayed). type Props = { grid: [], limit: number, }; type Sta ...

A step-by-step guide to invoking a function upon submitting a form with an external JavaScript file

How can I execute a function when the user submits a form using an external JavaScript file? index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>example</title> ...

Transforming a JSON String into a class that selectively uses properties from the JSON string

Currently, I'm facing a challenge with parsing the JSON string below: [ { "id": 1, "name": "Johnny" "dob": "12/10/1986" "sex": "Male" }, { "id": 2, "name": "Sarah" "dob": "3/7/1979" "sex": "Female" } ] ...

I am looking to update the appearance of a button dynamically in Vue.js based on changes to an

Is there a way to toggle a visible button when the array changes? I'm having trouble implementing this. What is the most effective method? Check out my example below: https://codesandbox.io/s/relaxed-poincare-vv6xh?file=/src/components/HelloWorld.vu ...

Assign the value from a drop-down menu to an SQL variable dynamically without the need for a submit button

I am trying to retrieve the value of the selected item in a drop-down menu populated from an SQL database. This value is essential for me to formulate the SQL statement required to access a specific record. The drop-down menu has already been populated. S ...

Best practices for selecting checkboxes and transferring values to another page in PHP/HTML

Apologies for my lack of experience in PHP. I am in the process of creating a project without any knowledge of PHP. I have set up a database with a list of users and can display users based on specific information through a search. Each search query has a ...

What is the process for determining the vertex position of geometry in three.js after applying translate, rotate, and scale transformations?

I've recently delved into the world of three.js. My current goal involves creating a curve within the scene and subsequently applying some transformations to it. The function responsible for generating the line is showcased below: var random_degree ...