JavaScript code can be used to access data from a JSON file and present the flower and color information in separate unordered lists

How can I retrieve data from a JSON file in JavaScript and display flowers and colors in separate unordered lists? I am having trouble adding it.

fetch('dataFiles/midterm.json', { 
      method: 'GET',
      mode: 'no-cors'
    })
    .then((response) => response.text())
    .then((data) => {
        //console.log(JSON.parse(data));
        //data =  response.text();
        alert(data);
        console.log(data);

        document.getElementById("data").innerHTML += "<ul></ul>";
        document.getElementById("data").innerHTML += "<ul></ul>";
    // Process data
    })
    .catch ( (err) => { // Handle Error
     });


// JSON Data:
{ "inventory": [ 
        {"type": "flower",
         "items": [
            { "name" : "Rose", "color" : "Red" },
            { "name" : "Daisy", "color" : "White" }]}, 
        {"type": "color",
         "items": [
            { "name" : "Blue", "shade" : "Sky Blue" },
            { "name" : "Green", "shade" : "Forest Green" }]}
            ] 
}

Answer №1

Generating HTML List Items

Your code currently adds <ul> elements but fails to include any actual list items <li>, resulting in empty display content.

To rectify this issue, construct an html string based on the retrieved data. Utilize both outer and inner forEach loops to showcase the "cars" array under each inventory type like flowers and colors.

You can employ template literals for composing the html structure and then exhibit the complete list within the designated data element as illustrated below.

Code Snippet

Check out the snippet execution to gain insights into its functionality.

let data ={"inventory":[{"type":"flower","cars":[{"make":"VW","model":"Bug","cost":24000},{"make":"GMC","model":"Suburban","cost":18000}]},{"type":"color","cars":[{"make":"VW","model":"Jetta","cost":25000},{"make":"Chevy","model":"Tahoe","cost":30000},{"make":"FORD","model":"F150","cost":29000},{"make":"HYUNDAI","model":"Elantra","cost":27500}]}};


// Triggered inside fetch.then(

let html = "";

data.inventory.forEach(item => {
  html += `<h4>${item.type}</h4><ul>`;
  item.cars.forEach(car => {
     html += `<li>${car.make}, ${car.model}, ${car.cost}</li>`;
  });
  html += "</ul>";
});

document.querySelector("#data").innerHTML = html;
h4 {
  background-color: steelblue;
  color:white;
  padding: 0.2rem;
}
<div id="data"></div>

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

Toggling checkboxes using Angular framework

Within my form, there is a table with checkboxes in each column. The table consists of 3 <tr> elements, and each <tr> uses ng-repeate to call the webservice and display clone data (in JSON format). Upon clicking a checkbox, I create a JavaScrip ...

Preview multiple images while uploading in a React JS application

In order to achieve multiple image upload with preview using React JS, I attempted the code below. However, I encountered an error in the console: Uncaught DOMException: Failed to set the 'value' property on 'HTMLInputElement': This ...

AngularJS File Input element triggering only once when selecting the same file

I have created an Angular directive to customize the file upload input. directive('ngFile', function () { return { link: function (scope, element, attrs) { var button = element.find('button[data-fileInputButton]&apos ...

The image is loaded correctly through the image picker, however, it is not displaying on the screen

When I click the button to pick an image from the gallery in this code, it is supposed to load the phone's gallery and display the selected image in the image component. Even though the image gets loaded properly (confirmed through test logs), it does ...

Managing active dropdown menus in VueJS

I'm having trouble figuring out why my navigation menu and method to open subitems on click are not working correctly. [![dropdown_menu][1]][1] new Vue({ el: '#app', data: { //menu "menu_title": "a", "child_ro ...

I am encountering difficulties adding an array to Firebase due to the lack of asynchronous nature in Node.js

As a beginner in the world of nodejs, angularjs and firebase, I am encountering issues related to the asynchronous nature of nodejs while trying to load data into firebase. My goal is to search an existing list in firebase, add a new element to it, and wri ...

Tips for customizing the IconButton appearance in material-ui

While Material-ui offers a default icon button, I am interested in customizing its design to resemble this: IconButton design needed Could you please advise me on how to make this change? Thank you. ...

Having trouble uploading an image using the Cloudinary API in a Next.js project

I am currently working on a page meant for creating posts. Initially, the page was designed to handle multiple image uploads. However, I made some adjustments so that it can now accept only a single image upload. Unfortunately, after this modification, the ...

"Exploring the Best Locations to Incorporate Plugins in VueJS Webpack

I am trying to incorporate Webpack provided Plugins in order to utilize JQuery globally. Some resources suggest You should add it in the webpack.config.js file under plugins:[] section. However, upon examining my webpack.config.js, I noticed that there ...

Store the fetched data as JSON in the local storage

Struggling to find a solution after reading several articles, I am working on fetching a large JSON from an API and I want to cache the response in the localStorage. The goal is for the script to check for an object with the requested ID in the cached JSON ...

What is the best way to showcase a value in JavaScript using CSS styling?

I'm looking to customize the background, font style, and outline for both open and closed elements in the code snippet below: a.innerHTML = "We are Open now now."; a.innerHTML = "We are Closed, arm."; Additionally, I want to appl ...

"The power of Node JS in handling JSON data and gracefully

I'm having trouble extracting a specific part of a JSON object in Node JS. When I print the response body, the entire object is displayed correctly. However, when I try to access object.subsonic-response, it returns NaN. I've spent a lot of time ...

How can I use AngularJS to initiate code to run after the view and controller have successfully synchronized a specific change?

I am currently using AJAX to load date ranges into a pair of SELECTs (managed with AngularJS ng-repeat), which are then transformed into a slider using jQuery UI's selectToUISlider. My concern is that selectToUISlider may behave unexpectedly if the SE ...

Utilize Typescript to aim for the most recent edition of EcmaScript

Are you looking to configure your typescript build to compile to the most recent version or the most current stable release of EcmaScript? For example, using this command: tsc --target <get latest version> Alternatively, in a tsconfig file: { & ...

Contrasting loading data from an empty state and having no items present

On my web page, I pull items from an API and display them. The API request is made in the created hook. I need to display a [loading] message while waiting for the API response, and a [no items] message if the loading is complete but there are no items ava ...

Can you explain the roles of client-side and server-side in Next.js?

Could someone please elaborate on the distinction between client side and server side in Next.js as detailed in their documentation? As far as I understand, Next.js operates on React which is client side and runs in the browser, while server side refers to ...

Adjust the itinerary's color using leaflet-routing-machine

Is there a way to change the color of the itinerary from red to a different color using the Leaflet routing machine library? I need to modify the styles option with the L.Routing.Line, but I'm not sure how to do it. import L from 'leaflet' ...

Is there a way to illuminate a complete row by simply hovering over a span within one of the columns?

If I want to change the background-color of a div with classes "row" and "highlightThisRow" when hovering over a span with the class "fromThisSpan", how can I achieve that? In a list, there are multiple rows with several columns. The span in question is l ...

Adjust the styling with jQuery according to the selected value from the dropdown menu

Check out this Fiddle I have a jQuery script that is supposed to change the style of an input box to display:block if the selected value is "<>" (Between). However, currently it is changing the css for all selected items instead of just the target i ...

How can I store the status of checked and unchecked checkboxes in an array of objects using Angular 7?

I have a set of checkboxes with a parent-child structure, and their values are generated dynamically in a loop. When I click the submit button, I want to capture the selected or unselected values in the specified format (as shown in the commented output) ...