Convert Array to an HTML Table Without jQuery – Quick Tip

← PrevNext →

Well, you don’t need any framework like jQuery, to convert an Array to an HTML table. In-fact, you can do this using pure JavaScript and with only a few lines of code. I’ll show you how.

The array, here in my example, is a JSON array. The array looks like this.

let arrItems = [
    {ID: '001', 'Bird Name': "Black Vulture", Type : 'Hawk'},
    {ID: '002', 'Bird Name': "Rock Pigeon", Type: 'Dove' },
    {ID: '003', 'Bird Name': "Bell's Sparrow", Type: 'Sparrow' }
  ];

It has just three JSON nodes, ID, Bird Name and Type.

The Script
<body>
  <div id='myTable'></div>
</body>

<script>
    let createTableFromArray = () => {
  
      // the array.
      let arrItems = [
        {ID: '001', 'Bird Name': "Black Vulture", Type : 'Hawk'},
        {ID: '002', 'Bird Name': "Rock Pigeon", Type: 'Dove' },
        {ID: '003', 'Bird Name': "Bell's Sparrow", Type: 'Sparrow' }
      ];

  
      // Get values for the table header.
      let col = [];
      for (let i = 0; i < arrItems.length; i++) {
        for (let key in arrItems[i]) {
          if (col.indexOf(key) === -1) {
            col.push(key);
          }
        }
      }

      // Create a Table.
      let table = document.createElement("table");

      // Create table header row.

      let tr = table.insertRow(-1);		// table row.

      for (let i = 0; i < col.length; i++) {
        let th = document.createElement('th');  // table header.
        th.innerHTML = col[i];
        tr.appendChild(th);
    
        th.setAttribute ('style', 
            'font:18px Calibri;border: solid 1px #DDD;' +
            'border-collapse: collapse; font-weight:bold;' +
            'padding: 2px 3px; text-align: center;');
      }

      // Add JSON to the table as rows.
      for (let z = 0; z < arrItems.length; z++) {
        tr = table.insertRow(-1);

        for (let j = 0; j < col.length; j++) {
          let tabCell = tr.insertCell(-1);
          tabCell.innerHTML = arrItems[z][col[j]];
          tabCell.setAttribute  ('style', 
            'font:18px Calibri;border: solid 1px #DDD;' +
            'border-collapse: collapse; ' +
            'padding: 2px 3px; text-align: center;');
        }
      }

      // Show the table.
      let container = document.getElementById('myTable');
      container.innerHTML = '';
      container.appendChild(table);
    }

    createTableFromArray();
</script>
Try it
That’s it. Its simple and you don’t need any framework to do this. JavaScript is enough. However, if you still want to use jQuery (for some reason) to convert an Array to a Table, then you must see this post.

Thanks for reading.

Articles you don't want to miss.

How to populate a SELECT Dropdown List with JSON Data using JavaScript
Dynamically add or remove Table rows in JavaScript and save data into a database
How to create a simple CRUD application using only JavaScript

← PreviousNext →