JavaScript Array of Objects To Table

JavaScript Array Of Objects To Table
Project: Make HTML table from JSON object with Vanilla JS
Author: Alexander Shoup
Edit Online: View on CodePen
License: MIT

This JavaScript code snippet helps you to generate an HTML table element from an array of JSON objects, where each object represents a row of the table. The JSON objects can have different properties, and the resulting table will have a column for each unique property across all objects.

How to Generate HTML Table from JavaScript Array of Objects

First of all, create a dive element with a class attribute of “table” in which the table will be generated through a JavaScript function.

<h1>Make table from JSON</h1>
<div class='table'></div>

Style using the table using the following CSS styles. These CSS rules are optional, you can use your own according to your needs.

* {
  font-family: sans-serif;
}

table {
  border-collapse: collapse;
  width: 100%;
}
.cd__main{
display: block !important;
}
th {
    padding-top: 12px;
    padding-bottom: 12px;
    text-align: left;
    background-color: grey;
    color: white;
}

td, th {
  border: solid 1px;
  padding: 8px;
}

h1 {
  text-align: center;
}

Finally, add the following JavaScript function to generate the HTML table from JSON objects.

var sample_json = [{
  header1: 'something',
  'Header 2': 'something else',
  header3: 'another something else',
  header5: 'everything'
  },
  {
  header1: 'something',
  'Header 2': 'something else',
  header3: 'anything at all',
  header4: 'another something else'
  },
  {
  header1: 'something',
  header3: 'anything at all',
  header4: 'another something else'
  }];

document.querySelector('.table').appendChild(makeTable(sample_json));

// return html table element from array of objects
function makeTable(json_objects_arr) {
  var table = document.createElement('table');
  var keys = getKeysFromArray(sample_json);
  table.appendChild(makeTHEAD(keys));
  table.appendChild(makeTBODY(json_objects_arr, keys));
  return table;
}

// make header row from array of keys
function makeTHEAD(keys) {
  var thead = document.createElement('thead');
  var tr = document.createElement('tr');
  keys.forEach(function(key){
    var th = document.createElement('th');
    th.textContent = key;
    tr.appendChild(th)});
    thead.appendChild(tr);
    return thead;
}

// make rows from key values in json
function makeTBODY(json, keys) {
      var tbody = document.createElement('tbody');
  json.forEach(function(object){
      let tr = document.createElement('tr');
    keys.forEach(function(key){
      var td = document.createElement('td');
      td.textContent = object[key];
      tr.appendChild(td);
    });
      tbody.appendChild(tr);
  });
    return tbody;
}

// return alphabetized array of keys from all objects in an array
function getKeysFromArray(json_objects_arr) {
  var array_of_keys = [];
  json_objects_arr.forEach(function(obj){
    Object.keys(obj).forEach(function(key){
      if (!(array_of_keys.includes(key))) {
        array_of_keys.push(key);
      }
    });
  });
  return array_of_keys.sort();
}

Code Explanation

This code defines a JavaScript variable sample_json as an array of three objects each of which has different properties (or keys) with corresponding values.

The code then uses document.querySelector() method to find the first element with the class .table and appends a dynamically created HTML table using the appendChild() method. The table is created by calling the makeTable() function and passing sample_json as an argument.

The makeTable() function returns an HTML table element that is created dynamically using the createElement() method. It also calls two helper functions, makeTHEAD() and makeTBODY(), to create the table header row and the table body rows respectively. makeTHEAD() takes an array of keys and creates a table header row with corresponding table header cells (th) for each key. makeTBODY() takes the original JSON data array and an array of keys and creates table rows with corresponding table data cells (td) for each key-value pair in each object.

Lastly, the code defines a helper function named getKeysFromArray() that takes an array of objects and returns an alphabetically sorted array of all unique keys in all objects.

Overall, the code generates an HTML table dynamically using a JSON array of objects and appends it to a specific HTML element on the page. The table includes all unique keys as table header cells and all corresponding key values in each object as table data cells.

That’s all! hopefully, you have successfully integrated a JavaScript array of objects into table’s source code. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply