Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a Table using JSON data from an API using Pure Javascript

I am currently using Jquery to populate a table with data from an API, but I want to do it without requiring any external libraries, is there a way to do this using pure javascript?

I currently use the following solution:

$.ajax({
url: 'http://localhost:2672/api/notes',
type: 'GET',
success: function (myNotes) {
    console.log(myNotes)
    // EXTRACT VALUE FOR HTML HEADER. 
    var col = [];
    for (var i = 0; i < myNotes.length; i++) {
        for (var key in myNotes[i]) {
            if (col.indexOf(key) === -1 && (key === 'title' || key === 'content' || key == 'category')) {
                col.push(key);
            }
        }
    }

    // CREATE DYNAMIC TABLE.
    var table = document.createElement("table");

    // CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.

    var tr = table.insertRow(-1); // TABLE ROW.

    for (var i = 0; i < col.length; i++) {
        var th = document.createElement("th"); // TABLE HEADER.
        th.innerHTML = col[i];
        tr.appendChild(th);
    }

    // ADD JSON DATA TO THE TABLE AS ROWS.
    for (var i = 0; i < myNotes.length; i++) {

        tr = table.insertRow(-1);

        for (var j = 0; j < col.length; j++) {
            var tabCell = tr.insertCell(-1);
            tabCell.innerHTML = myNotes[i][col[j]];
        }
    }

    // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
    var divContainer = document.getElementById("showNotes");
    divContainer.innerHTML = "";
    divContainer.appendChild(table);
}
});
like image 741
Frink Avatar asked Aug 23 '26 16:08

Frink


1 Answers

If we do it the modern way, it is not that much code. This will work in Chrome / FF and any other modern browser. Note, that I fake-load JSON in Fetch API Promise's catch clause for demo purposes, you should obviously remove it in your code.

Once you grasp how you can use map() and reduce() to manipulate collections of data, it will simplify the code a lot.

The code below can be much shorter, but I wanted to provide some readability.

const wrapper = document.getElementById('content');

const demoData = [
  {"id":1, "name":"John", "age":21},
  {"id":2, "name":"Bob", "age":19},
  {"id":3, "name":"Jessica", "age":20}
];

function fetchData() {
  fetch("data.json")
      .then(data => data.json())
      .then(jsonData => populate(jsonData))
      .catch(e => {
          wrapper.innerText = "Error: "+e+" going to use demo data";
          populate(demoData); //remove me
      });
};

document.addEventListener('DOMContentLoaded', fetchData, false);

function dom(tag, text) {
    let r = document.createElement(tag);
    if (text) r.innerText = text;
    return r;
};

function append(parent, child) { 
  parent.appendChild(child); 
  return parent; 
};

function populate(json) {
    if (json.length === 0) return;
    let keys = Object.keys(json[0]);
    let table = dom('table');
    //header
    append(table,
      keys.map(k => dom('th', k)).reduce(append, dom('tr'))
    );
    //values
    const makeRow = (acc, row) =>
        append(acc,
            keys.map(k => dom('td', row[k])).reduce(append, dom('tr'))
        );
    json.reduce(makeRow, table);
    wrapper.appendChild(table);
};
<!DOCTYPE html>
<html>
<body>
<div id="content"></div>
</body>
</html>
like image 71
Alex Pakka Avatar answered Aug 26 '26 06:08

Alex Pakka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!