Leverage JSON data to generate individual elements, rows, and columns for every object within the array

Just starting out with JavaScript and struggling a bit. We need to fetch data from this URL: and then manipulate the data to create new rows (tr) and columns (td) for each game without altering the HTML file. The desired outcome should resemble this: https://i.sstatic.net/3ejGx.png

I'm having trouble understanding how to iterate through the data and utilize it effectively.

import {getData} from './getdata.js';
let data = getData();
event();

function createTR(text) {
    var x = document.createElement("TR");
    x.setAttribute("class", "myTr");
    document.getElementById("table").appendChild(x);
  
    var y = document.createElement("TD");
    var t = document.createTextNode(text);
    y.appendChild(t);
    document.querySelector(".myTr").appendChild(y);
}

function event() {
    document.querySelector('#active').addEventListener('click', myFunction);
}

function myFunction() {
    data.then(createTR);
}

export function getData() {
    return fetch('https://stryk.herokuapp.com/tipset')
        .then(function (response) {
            return response.json();
        })
        
        .then(function (data) {
            console.dir(data);            
                
            });
        }
            

Answer №1

Do I understand correctly that you are asking how to traverse multiple elements in JSON data using JavaScript? If so, you will need to follow three steps.

Begin by converting the JSON data to an object:

   var jsonData = JSON.parse(data)

Next, retrieve an array of keys from the object:

   var keysArray = Object.keys(jsonData)

Finally, iterate through the object using a for loop:

   for (var i = 0; i < keysArray.length; i++) {
      var value = jsonData[keysArray[i]] 
      // Create a new row with the data
   }

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

Is it possible to generate various resolutions of an image simultaneously?

While trying to download wallpapers from a link on this website, I encountered an issue. Upon clicking the download button, a new page opened with the URL "https://images.wallpapersden.com/image/download/street-fighter-fortnite_bGtoaW6UmZqaraWkpJRmbmdlrW ...

The combination of Material UI custom TextField and Yup does not seem to be functioning properly

I am facing an issue with integrating my custom TextField into my RegisterForm along with Yup validation. Whenever I use the custom TextField, I encounter a message "⚠ Champ obligatoire" after clicking on Submit, which is not the case when using a simple ...

Information within specified dates shows all leaders

Looking to filter data based on Start Date, End Date, and HeadName. The current search query successfully filters between dates but does not properly filter the HeadName column, displaying all results instead. Sno HeadName Date Amount BillNo BillD ...

Why is the React onClick method returning undefined upon the first selection, and why are the values being passed not consistent with

While attempting to create a list of users that, when clicked, should open up a corresponding user's message, I encountered an issue where clicking for the first time resulted in an 'undefined' value being passed. I've tried troublesho ...

Read JSON files and save them directly to Hadoop before querying it for the necessary data

For my project, a large amount of data is received from the server in JSON format. We have set up a cron task to run every hour to retrieve this data, which is then saved into a file for analysis purposes. This data contains numerous measurement points tha ...

Discovering numbers within a JSON object and extracting them - a step-by-step guide

If I have a JSON object coming from a random dataset and want to search through it to manipulate the number values, how can I achieve this? Looping through the object using for...of allows me to get the keys, but I'm unsure how to access every key-val ...

`Unexpected error occurred during JSON parsing due to a unrecognized selector being sent to the

Can someone assist me in debugging this piece of code? dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(queue, ^{ NSError *error = nil; NSURL *urls = [NSURL URLWithString:[NSString stringWi ...

Decoding whole numbers using JsonCpp

Currently, I am utilizing JsonCpp version 1.6.5 for the parsing of a JSON file that includes the following content: { "some-property" : 32 } Upon parsing, it appears that the type of the value is recognized as intValue instead of uintValue. I am curious ...

Maximizing React Performance: Strategies for Avoiding Unnecessary Renderings on State Updates

I am facing a major performance issue due to constant re-rendering of my child components on every state change. I need a solution to prevent this from happening and maintain the stability of my application. Any suggestions or guidance would be highly ap ...

When using Angularjs and UIRouter, calling event.preventDefault() will prevent the default browser behavior and

A custom JavaScript prompt is triggered when a user clicks the back button on their browser by monitoring the $stateChangeStart event. Let's explore this scenario: Imagine users moving through pages 1, 2, and finally reaching page 3. Upon trying to g ...

Tips for populating a Flat List with nested JSON data in React-Native

As a beginner in React-Native and Javascript, I'm trying to figure out how to retrieve data for my FlatList. The JSON format I receive is structured like this: [ { "18": { "sellingUnitName": "unité(s)", "qualifier": "GOOD", " ...

I'm having issues with npm installation, receiving a "module not found" error. I've

My experience with installing modules has been smooth so far, but recently I encountered an issue without changing my usual workflow. I executed: npm i --save mariadb in the main directory of my Node project. Then, I imported the module as follows: con ...

Module child-process not found

Why is it that when I try to run "require('child-process')" in the node shell, I receive an error saying "Cannot find module 'child-process'"? It seems like "child-process" should be a default library in Node. Any insights on what could ...

Component re-rendering and initializing useReducer

I made some revisions to this post. Initially, I shared the entire problem with my architecture and later updated it to focus directly on the issue at hand in order to make it easier for the community to provide assistance. You can now jump straight to the ...

What is the method to determine the number of bits in a byte array?

Currently, I am working on developing a download speed test. Specifically, I am in the process of downloading an 800 megabit file into a Byte[] within a memory stream using the following code: webClient.DownloadDataAsync(new Uri(link), memStreamArray); I ...

Exploring ways to pass props in functional components in React Native

I am currently exploring how to create an API in React Native with TypeScript without using the class extends component. However, I am struggling to figure out how to access and send props from one const view to another function: App.tsx import React, {us ...

Tips for troubleshooting my website?

After making some updates to my website, I noticed that an ajax script is no longer functioning properly. Since I hired someone else to write the code, I'm not sure how to troubleshoot it. Initially, this is what it should look like: When you select ...

Implementing a color change for icons in React upon onClick event

export default function Post({post}) { const [like,setLike] = useState(post.like) const [islike,setIslike] = useState(false) const handler=()=>{ setLike(islike? like-1:like+1 ) setIslike(!islike) } return ( <> <div classNam ...

How to dynamically apply component-specific CSS in NextJS based on conditions

I'm working on my nextjs project and encountered an issue with adding conditional styling to a component. To address this, I created a component-level stylesheet called MyComponent.module.css, which includes the following styles: .primary { color: ...

JavaScript code to allow two textboxes to be enabled at the same time when a checkbox is

One question I have regarding the code snippet below : <input id="myCheckBox" type="checkbox" name="alamatCat" onClick="apply(this.checked, 'textBox3', 'textBox4')"> OT Date </td> <td> From <input id="text ...