JavaScript: Render an array of objects in an HTML table

Updated: February 2, 2024 By: Guest Contributor Post a comment

Introduction

Rendering data in a table format is a common requirement for web developers. Whether you’re displaying users’ information, product details, or financial records, tables provide a structured way to present data. In this tutorial, we will learn how to render an array of objects into an HTML table using JavaScript. We’ll cover the basics and then dive into more complex scenarios including dynamic creation and handling of tables with large datasets.

Basic Table Rendering

Let’s start with the basics. Imagine we have the following array of objects:

const users = [
  { id: 1, name: 'Alice', email: '[email protected]' },
  { id: 2, name: 'Bob', email: '[email protected]' },
  { id: 3, name: 'Charlie', email: '[email protected]' }
];

To display this data in an HTML table, we first need a table element in our HTML:

<table id="usersTable">
  <thead>
    <tr>
      <th>ID</th>
      <th>Name</th>
      <th>Email</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>

Now, let’s write some JavaScript to dynamically fill the table with our users’ data. We’ll loop through the array and append each object’s values into the table:

function populateTable(users) {
  const table = document.getElementById('usersTable').getElementsByTagName('tbody')[0];
  users.forEach(user => {
    let row = table.insertRow();
    let idCell = row.insertCell(0);
    idCell.textContent = user.id;
    let nameCell = row.insertCell(1);
    nameCell.textContent = user.name;
    let emailCell = row.insertCell(2);
    emailCell.textContent = user.email;
  });
}

populateTable(users);

Handling Large Datasets

When working with large datasets, performance can become an issue. To mitigate this, it’s beneficial to build and append the table rows in batches or even consider virtual scrolling techniques. Here, we’ll focus on improving performance by reducing DOM manipulations.

function populateTableEfficiently(users) {
  const tableBody = document.createElement('tbody');
  users.forEach(user => {
    let row = document.createElement('tr');
    for (const key in user) {
      let cell = document.createElement('td');
      cell.textContent = user[key];
      row.appendChild(cell);
    }
    tableBody.appendChild(row);
  });
  document.getElementById('usersTable').appendChild(tableBody);
}

populateTableEfficiently(users);

Dynamic Table Creation

Sometimes, you won’t have an existing table in your HTML and you’ll need to create it dynamically. Here’s how you can do it:

function createAndPopulateTable(users) {
  let table = document.createElement('table');
  let thead = document.createElement('thead');
  let tbody = document.createElement('tbody');
  let headerRow = document.createElement('tr');

  ['ID', 'Name', 'Email'].forEach(headerText => {
    let header = document.createElement('th');
    header.textContent = headerText;
    headerRow.appendChild(header);
  });

  table.appendChild(thead);
  thead.appendChild(headerRow);
  table.appendChild(tbody);

  users.forEach(user => {
    let row = tbody.insertRow();
    let idCell = row.insertCell(0);
    idCell.textContent = user.id;
    let nameCell = row.insertCell(1);
    nameCell.textContent = user.name;
    let emailCell = row.insertCell(2);
    emailCell.textContent = user.email;
  });

  document.body.appendChild(table);
}

createAndPopulateTable(users);

Conclusion

In this tutorial, we’ve explored different ways of rendering an array of objects in an HTML table using JavaScript. Starting with basic table population, we moved on to handling large datasets more efficiently and even dynamically creating tables on the fly. The techniques presented here form a foundation upon which you can build more complex and interactive table-based user interfaces.

Remember, the key to efficient web development is understanding the tools and techniques at your disposal and knowing when and how to apply them. With practice, you’ll be able to implement these solutions and adapt them to fit your own unique requirements.