Using javascript to fetch JSON Objects

Struggling with fetching JSON objects and need help accessing the data within the "choices" key. Grateful for any guidance you can provide.

Answer №1

Example of a loop

for (let i = 0; i < data.questions.length; i++) {
    console.log(data.questions[i].choices.a);
    console.log(data.questions[i].choices.b);
}

Answer №2

Iterating through the questions array to display choices for each question:
for (let i=0; i<questions.length; i++) {
    let options = questions[i].choices;
    console.log(options.A);
    console.log(options.B);
}

Answer №3

If you've defined a variable assignment like var myobj = { ... } where the ... represents your JSON object in the post, then to access all the data points related to choices, you can use the following code snippet:

myobj.questions[0].choices.a
myobj.questions[0].choices.b
myobj.questions[1].choices.a
myobj.questions[1].choices.b

Are you looking for a more specific explanation on how to iterate through all questions and choices?

Note: Based on your comment, it seems that you might be interested in something similar to this code block:

for (var qi=0; qi < myobj.questions.length; qi++) {
    var q = myobj.questions[qi];
    console.log(q.ques);
    for (var choiceKey in q.choices) {
        console.log("    " + choiceKey + " --> " + q.choices[choiceKey]);
    }
}

You can modify the logic within the loops as per your requirements. Running the above code with your example JSON will produce output like below:

how old are you?
    a --> 19
    b --> 20
question two?
    a --> answer1
    b --> answer2

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

Maintaining awareness of which accordion drawer is currently open within a React application

Just getting started with coding, I recently created a collapsible accordion in a NextJs app using the react-collapse package. Everything seems to be working fine, but I'm running into an issue with keeping track of which 'drawer' is current ...

"Utilizing Object.call() in JavaScript for inheritance yields an undefined result

I have been working on implementing an object-oriented approach in my program. According to what I've learned, there should be an inheritance relationship between World and Sprite classes, with Sprite as the parent. However, when I try to call Sprite. ...

What is the best way to add user login information to the request pipeline in Express.js?

In my current project, I've been working on a middleware that is responsible for extracting the user model and attaching it to the request pipeline. Although I have successfully implemented a token extractor middleware that attaches the token to the r ...

Minimize/Maximize Swagger Response Model Class View

After successfully integrating Swagger API documentation with my rest services, I encountered a challenge. The Swagger page appears too lengthy due to the numerous response classes in my project, requiring users to scroll extensively to find information. ...

Turn off and then reinstall Image when clicked

function show(){ alert("i am pixel"); } function disableImgClick(){ $(".Dicon").unbind('click'); } $(document).ready(function(){ $("#turnoff_btn").click(function (e){ e.preventDefault(); disableImgClick(); }); }); i have a group of ima ...

When you zoom in, the HTML elements tend to shift out of place

Spent the entire day yesterday attempting to make my page responsive while Zooming In, but I just can't seem to get it right. Even after adding height and weight, elements still get mixed up when zooming in on the page. I've scoured countless w ...

Meteor push/browserhistory fails to navigate or refresh to a different page

Currently, I am attempting to set it up so that when a user clicks on a profile, they are redirected to the profile page of the user they clicked on. Here is the code I am using: const self = this; browserHistory.push({ pathname: '/user ...

Tips for making Slider display the next or previous slide when span is clicked

I have implemented a mix of bootstrap 3 and manual coding for my project. While the image thumbnails function correctly when clicked, the span arrows do not navigate to the next or previous images as intended. Below is the code snippet: var maximages ...

Retrieve the scrolling height in Vue.js 2 window

I need to apply the sticky class to the navbar when a user scrolls down, and remove it when they scroll back up. To achieve this, I am attempting to calculate the scrolled height. Currently, my code looks like: mounted(){ this.setUpRoutes(); wind ...

The property fails to reflect changes in state

I am currently developing an application that requires fetching data asynchronously and preserving the state in the parent component while also passing the data reference to children components. I encountered an issue where the props do not update when the ...

Orbit around a moving object in Three.js

I am working with a camera that needs to rotate around a specific target position within the scene. Despite attempts to implement a pivot concept, as suggested in this discussion: https://github.com/mrdoob/three.js/issues/1830, I have come up with my own s ...

The unexpected postbacks caused by the ASP.NET MVC DropDownList appear to stem from JavaScript, catching me by surprise

In my MVC project, there's a standard form with a dropdown list. Each time I change the dropdown value, the entire page reloads due to a postback. This behavior is unexpected, and I want to prevent the dropdown from triggering a postback. Strangely, ...

Showing a React Portal Toolbar only when populated with children

OBJECTIVE: The objective is to show the ToolkitArea only when there are children present in "#toolkitArea". CHALLENGE: Unable to accurately determine the number of children inside the ToolkitArea. ACTIONS TAKEN SO FAR: I have developed a component calle ...

Showcase the Uploaded Image Section within the Dropzone Display

https://i.sstatic.net/xzJWT.png Hello! I am currently working on implementing Dropzone.js to create a gallery. I've encountered a small issue where the default behavior of Dropzone displays a blank container area with a clickable effect to upload pho ...

Error: Property 'blogCategory' is unreadable because it is undefined

Having trouble rendering blog posts from a json file in React const BlogPost = (props) => { const [post, setPost] = useState({ id: "", blogCategory:"", blogTitle:"", postedOn:"", ...

Create a custom element in React to detect and encapsulate links

I could really use some assistance with this issue. I have a bunch of text blocks containing links and have been utilizing linkifyjs's React component to automatically wrap the links in anchor tags. However, now I am looking to add a custom button nex ...

What are the steps to viewing an image or video file in full screen mode on a web browser?

Is there a way to play video/image files in full screen mode on a browser? How can I achieve this? ...

Error message: jQuery DataTables encountering issues with POST Server Side JSON communications

My table is not loading correctly via ajax. Here is the JavaScript code I am using: $('#initAjaxDataTable').DataTable( { "pagingType": "full_numbers", "processing": true, "serverSide": true, "ajax": { "url": $('#ini ...

Having trouble retrieving the complete URL on the Login Page within Shopify

I've been working on a feature where users are redirected to different URLs based on the page they click the login button on. For example, I have a registration page and a regular page, both with a login button. When a user clicks the login button on ...

Here's the proper method to execute this in JavaScript

Hello everyone, thank you for stopping by. I'm trying to figure out the correct way to achieve the following: <script language="javascript"> function flag(nation) { this.nation=nation; document.getElementById("flag").innerHTML="<img src=&ap ...