A guide on retrieving an array object from a JSON file

Here is the JSON link: https://www.cc.puv.fi/~asa/cgi-bin/fetchOrders.py

I am currently able to fetch objects, but I am experiencing difficulty in fetching arrays within the object as well.

Can someone guide me on how to also fetch the "products" arrays?

This is the javascript code I am using:

fetch('https://www.cc.puv.fi/~asa/cgi-bin/fetchOrders.py')
  .then(res => res.text())
  .then(text => displayData(text))

function displayData(data) {
    console.log(data);
    let orders = JSON.parse(data);
     console.log(orders);

    let table = "<table><tr><th>orderid</th><th>customerid</th><th>customer</th><th>invaddr</th><th>delivaddr</th><th>deliverydate</th><th>respsalesperson</th><th>comment</th><th>totalprice</th></tr>";
    for(let i = 0; i < orders.length; i++) {
        let order = orders[i];
        console.log(order)
        console.log(order.orderid);
        table += '<tr><td>' + order.orderid + '</td><td>' + order.customerid + '</td><td>' + order.customer + '</td><td>' + order.invaddr + '</td><td>' + order.delivaddr + '</td><td>' + order.deliverydate + '</td><td>' + order.respsalesperson + '</td><td>' + order.comment + '</td><td>' + order.totalprice + '</td></tr>'
    }   
    console.log(table);
    document.getElementById('info').innerHTML = table+'</table>';
}

Answer №1

You may have successfully retrieved the products array, but you still need to incorporate some code for iterating through it.

    for(let i = 0; i < orders.length; i++) {
        let order = orders[i];
        console.log(order)
        console.log(order.orderid);
        a += '...'

        for (let j=0; j < order.products.length; j++) {
          console.log(order.products[j].name);
        }
    }

Instead of using console log within the loop, consider implementing code that writes to the HTML like you were previously doing. Depending on your desired layout, this could be challenging, so think about abstracting HTML generation or utilizing a UI component library.

Answer №2

    fetch("https://www.cc.puv.fi/~asa/cgi-bin/fetchData.py").
        then(response => response.json())
        .then(info => displayInfo(info))

    let displayInfo = (info) => {
        for (let index = 0; index < info.length; index++) {
            let items = info[index].items 
            // this items variable holds an array of objects

            for(let j=0;j<items.length;j++){
                let item = items[j];
                console.log(item)
                // you can access properties like item.id to get the id
            }
           
        }
    }

Answer №3

When iterating through the array, be sure to access the product object within each array value (tialus.products). Save that value in a variable for easy reference.

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

Trimming REST responses

Imagine I develop an API endpoint that provides the following response: [ { "timestamp": 123456789, "average": 0.0123456789 }, ^^ multiple instances ] Is it acceptable to abbreviate the labels, for example: changing "ti ...

What is the recommended approach for safely sanitizing HTML within ExtJS applications?

Currently, I am in the process of developing a web application utilizing ExtJS for creating the graphical user interface and interacting with the server through RESTful web services (where data is returned in JSON format). However, I have encountered chall ...

Exploring Type Refinements with Flow

I keep encountering an issue indicating that 'The operand of an arithmetic operation must be a number.' despite having a runtime check at the beginning of the function to confirm that this.startedDateTime is indeed a number. I am puzzled as to wh ...

Utilizing AngularJS to organize an external JSON file into an HTML table

I am facing an issue with sorting JSON data from an external file in AngularJS. I can easily sort the data when I declare JSON internally as an array, but I cannot retrieve the data when it's declared in an external file. Can someone assist me with th ...

How can I utilize JavaScript to call a Delphi function in TWebBrowser on Delphi XE6 for all platforms, such as iOS and Android?

My goal is to develop an application using Delphi XE6 for Android and iOS that utilizes a TWebBrowser to display Google Maps. I need the ability to communicate between Delphi and JavaScript, allowing me to interact with markers on the map based on user inp ...

How to Calculate Dates in Javascript

Currently exploring the realm of JavaScript, I find myself in the process of developing a dashboard for an e-commerce platform that I am currently involved with. My goal is to display data for all dates starting from the date of the initial order placed. M ...

The AJAX request was successful, however, the PHP script did not return any

When using an Ajax success function to alert data in JavaScript, there may be occasions where the PHP side shows that the GET array is empty. <script type="text/javascript"> var myArray={ name:"amr", age:22 } myArray =JSON.stringify(myA ...

Obtaining the top 5 elements with UnderscoreJS using the _.each function

I have an array of objects and I am able to access the properties of each object using the _.each method, which is working perfectly. var x = [{id:1, name:"xyz"},{id:2, name:"pqr"},...and so on] Currently, I am accessing them using the _.each method as s ...

Error encountered with Ajax client-side framework while executing HTML code

When I run my project from Visual Studio using an aspx page that utilizes ajax modal popup extender, everything works fine with IE and Firefox as the default browsers. However, when I create an HTML file containing the code and open it by double-clicking, ...

Can you explain the meaning behind the exclamation mark in Angular syntax?

I've noticed this popping up in a few spots lately, but I haven't been able to find any information about it. I'm intrigued by the use of the '!' symbol in Angular syntax. Can anyone explain what it does? https://i.sstatic.net/sj ...

Updating a function by passing in arguments in JavaScript

I am currently using Winston as the logger for my Node.js application. Within my script, I have a line that looks like this: log.error("my error", {input: [1,2]}); When I check the console, I see the following output: error: my error input=[1, 2] What ...

Generating a series of DIV elements using the DOM and attaching them to the primary DIV

I am attempting to dynamically create 121 divs using the DOM and then add them to the .container div const container= document.querySelector('.container'); const divNumber= 121; for (let i= 0; i<= 121; i++){ ...

C++ static class template featuring a constant array of function pointers

Looking for guidance on creating a templated class with an array of function pointers in C++, but struggling with the syntax. Here's what I have so far: --myclass.h-- #include <vector> template <typename T> class MyClass { typedef v ...

Analyzing values passed from Java using PHP

Currently, I am in the process of working on two PHP files: login.php and DB_Functions.php. Within these files, there is a particular script that receives a password and email from the application. It then locates the specific user using the provided emai ...

Comparing innerHTML in JavaScript: A guide to string comparison

While attempting to filter a table alphabetically, I encountered an obstacle. The x.innerHTML > y.innerHTML concept in this code snippet is perplexing me: table = document.getElementById('myTable'); rows = table.getElementsByTagName('t ...

NodeJS process that combines both client and server functionality

Attempting to develop a test echo server with both client and server in the same node process. When the code is split into two files (server and client), it functions correctly, but when combined into one file, it fails. How can I make it work within a sin ...

Transferring form data to JavaScript for executing jQuery/AJAX request to fetch information from the database – what a journey!

Currently, I am attempting to extract a zip code from my form and then submit it to JavaScript/jQuery to retrieve data from the database associated with that specific zip code. After copying some code from w3schools and making a few modifications, as well ...

Using the useRef hook to target a particular input element for focus among a group of multiple inputs

I'm currently working with React and facing an issue where the child components lose focus on input fields every time they are re-rendered within the parent component. I update some state when the input is changed, but the focus is lost in the process ...

What strategies can be employed to minimize redundant re-rendering of React components while utilizing the useEffect hook?

Hey everyone, I'm facing a challenge in my React/Electron project where I need to minimize renders while using the useEffect hook to meet my client's requirements. Currently, I have a container/component structure with an index.js file that house ...

Guide on how to send files to an API using a form in React with MUI

I am struggling with sending an image through the front-end to my back-end application that is set up to accept data. Here is the code I have: import { useState } from 'react'; import axios from '../../config'; import { useNavigate } fr ...