Categories
JavaScript Answers

How to Parse JSON Arrays and Display the Data in an HTML Table with JavaScript?

Spread the love

To parse JSON arrays and display the data in an HTML table with JavaScript, we can loop through each entry of the array, create tr elements for each, and insert them into the table element.

For instance, we write:

<table>

</table>

to create the table element.

Then we write:

const data = [{
  "User_Name": "John Doe",
  "score": "10",
  "team": "1"
}, {
  "User_Name": "Jane Smith",
  "score": "15",
  "team": "2"
}, {
  "User_Name": "Chuck Berry",
  "score": "12",
  "team": "2"
}]

let tr;
for (const d of data) {
  tr = $('<tr/>');
  tr.append(`<td>${d.User_Name}</td>`);
  tr.append(`<td>${d.score}</td>`);
  tr.append(`<td>${d.team}</td>`);
  $('table').append(tr);
}

to put the content of data into a table.

We loop through data with a for-of loop.

Then in the loop body, we create a tr element with $('<tr/>').

Then we append the td elements for each column with:

tr.append(`<td>${d.User_Name}</td>`);
tr.append(`<td>${d.score}</td>`);
tr.append(`<td>${d.team}</td>`);

Then we append the tr element with the content to the table element with:

$('table').append(tr);

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.