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:

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

"Critical issue: Meta tags are not present on the dynamic pages of the NextJS

In my NextJS application, the pages are structured as follows: App --pages ----_app.js ----index.js ----company.js ----users ------[userID].js I have a dynamic page named [userID].js that retrieves the userID through the router to display information for ...

Ways to manage your javascript variables

Here is the code snippet I am working with: var json = jQuery.parseJSON(data); console.log(json) When I run this code, the output looks like this: Object {sql: "SELECT venta.cliente_tipodoc,count(*) AS cantidad FROM venta venta", results: Array[1], ...

A specialized identifier for nested objects in a React component

I am currently working with a JSON data structure that looks like this: [ [ { city: x patients: x id: 1 }, { city: y patients: y id: 2 } ], [ { city: x patients: x id: 1 }, { city: y patients: y id: 2 } ...

Troubleshooting: Issues with Jquery's replaceWith function

I'm facing an issue with a table I have that includes a button in one of its columns. The button is supposed to toggle the class of the current row in the table and then replace itself once clicked. $(document).ready(function() { $(".checkOut"). ...

Attempting to call a Struts 2 action class from AngularJS using an HTTP GET request, however, no response is being received

I have been working on a simple application that involves making a call to Struts 2 through AngularJS. The process includes sending an HTTP GET request from AngularJS to fetch JSON data from the server. On the server side, I have created an action class na ...

Adding the <a> tag causes Superfish to malfunction

I've been struggling to get the latest Superfish menu code working with lists that include the <a> tag. I've double-checked everything, but it seems like I'm missing something obvious. Can anyone help me figure out what's wrong? ...

next-redux-wrapper is being invoked repeatedly and experiencing multiple calls to HYDRATE

I'm embarking on a new Next.js project, transitioning from a standard React app to a Next.js application. Our plan is to utilize Redux Toolkit for global state management and incorporate server-side rendering. During this process, we discovered the ne ...

Enhancing the Performance of jQuery Scripts

My jQuery function called textfill is utilized on numerous div elements. Essentially, it resizes the text inside each div to perfectly fit the container so that longer texts are made smaller than shorter ones while maintaining the maximum font size without ...

sending information back to the controller with get method (ajax, javascript)

I'm currently facing a challenge where I have an event listener waiting for a button to be pressed. Once the button is pressed, the controller method 'update' is called which then triggers the view method 'input' to fetch data from ...

Ways to transfer a jQuery variable value to a PHP variable

I am trying to transfer a jQuery variable value to a PHP variable on the same page using AJAX in my JavaScript code. I have attempted to print the PHP variable but encountered an error. Any assistance would be greatly appreciated. <script type="text/ ...

Tips for breaking up array elements across multiple "tr" tags

In this particular example, I have a Fiddle set up with multiple tr elements displayed within an ng-repeat. My goal is to have three td elements per row. Would it be necessary to use an inner angularjs ng-repeat and split the iconDets array for this purpos ...

Tips for resolving error "Exception in main thread java.lang.NoClassDefFoundError: com/fasterxml/jackson/annotation/JsonView":

I am attempting to assess a json string by utilizing the jackson library's ObjectMapper. I have included the jackson-annotation, jackson-databind, and jackson-core dependencies with the matching version in the pom.xml file. However, the code is produc ...

Ways to verify the existence of a username in WordPress without the need to refresh the page

How can I check if a username exists in the database without refreshing the page in a Wordpress form using AJAX? I've tried implementing AJAX in Wordpress before but it didn't work. Can someone provide me with a piece of helpful code or a link to ...

Retrieve JSON data in camelCase format from a Web API

My goal is to retrieve camel cased JSON data from an ASP.Net Web API 2 controller. To achieve this, I set up a new web application specifically with the ASP.Net MVC and Web API components. I modified the ValuesController as shown below: public class Value ...

Send a request to templateUrl

After experimenting with AngularJS, I decided to create a dynamic route system that funnels all routes through a single PHP file. This was motivated by my desire to prevent users from accessing raw templateUrl files and seeing unstyled partial pages. Prio ...

What steps are needed to enable the keyboard on a Otree application for mobile devices?

I previously utilized an Implicit Association Task (IAT) in an experiment conducted on computers. However, I now need to adapt this IAT for use on tablets or mobile devices. Here is how the IAT appears on a cellular device: https://i.stack.imgur.com/kNwo ...

Anticipating 'STRING', received 'EOF'

I am in the process of creating a config.gateway.json file for my Ubiquiti firewall and now I need to upload the file. When I try to run this configuration on jsonlint.com, I encounter the following issue: { "LOAD_BALANCE": { "description": "LO ...

Attempting to refresh a function when an image is clicked

I'm facing an issue with reloading a function in my code that involves a JSON file. The function should display the correct item on the page when you click on a related product image, but I haven't been able to get it working properly. Any guidan ...

Sometimes Node.js' Express.js fails to send valid JSON

Below is the express code snippet app.post('/v1/sessions' function(req,res){ res.send({id:1234}); }); Unexpectedly, the json response displays as follows: OK{ id: 1234} Questioning the presence of the 'OK' UPDATE Upon reviewin ...

The jQuery function .val()/.text() is unable to retrieve information from a particular section of HTML

Implementing HandlebarsJS with PHP and Yii to generate a page. Here is a snippet of the html/handlebars code on the page {{#if embed_link}} <p class='f_hidden_p'> <a href='{{embed_link}}'> {{ ...