Menahem Gil
Menahem Gil

Reputation: 829

Create a table with data from REST API call using Javascript

I need to create a table from JSON data that I get from a REST API. The problem: for this specific app, I can't use Angular.

My question is: do I have to use var table = document.createElement("TABLE"); in the script and create the whole table in the script? Or there's nicer / elegant way to separate the code and in the .html file to build the table?

In other words, something that is more similar to the one way data binding in Angular. So far I only used angular to work with REST API, but for this specific project I have to use Vanilla.

Thanks.

Upvotes: 0

Views: 2099

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371049

It's really easy to accomplish in vanilla JS, it just takes some lines - just keep appending elements and iterating. For example

const input = [
  { foo: 'f', bar: 'b' },
  { foo: 'ff', bar: 'bb' },
  { foo: 'fff', bar: 'bbb' },
  { foo: 'f', bar: 'b' },
];
const table = document.body.appendChild(document.createElement('table'));
const thead = table.appendChild(document.createElement('thead'));
const tr = thead.appendChild(document.createElement('tr'));
const columnTexts = Object.keys(input[0]);
columnTexts.forEach((columnText) => {
  tr.appendChild(document.createElement('td'))
    .textContent = columnText;
});
const tbody = table.appendChild(document.createElement('tbody'));
input.forEach((item) => {
  const tr = tbody.appendChild(document.createElement('tr'));
  const values = Object.values(item);
  values.forEach(value => {
    tr.appendChild(document.createElement('td'))
      .textContent = value;
  });
});

Upvotes: 1

Related Questions