how to create a table to display an array

Asked

Viewed 43 times

0

I have the Following Code

function imprimirArray(id, array) {
      let span = document.getElementById(id);
      span.innerHTML = '';

      for (let i = 0; i < array.length; i++) {
        span.innerHTML +=  'pontuação: ' + array[i].soma + ', Categoria: ' + array[i].categoria + ' <br/>';
      }
    }

but I want instead of displaying the data next to each other to be in table

  • You can show an example of the structure of this array?

  • 3

    the structure of a table, for each interaction of for has to generate a line tr and a td for each property, just change this and your table will be ready

1 answer

1

To generate a table with dynamic data a minimum example has been created:

const arr = [
  {soma: 100, categoria: "cat1"},
  {soma: 200, categoria: "cat2"},
  {soma: 300, categoria: "cat3"}
];

function imprimirArray(id, array) {
  var table = document.getElementById(id);
  if (table) {
      for(let i = 0; i < array.length; i++){
          var row = table.insertRow(i); // cria a linha
          var cell1 = row.insertCell(0); // cria uma célula na linha
          var cell2 = row.insertCell(1); // cria a outra célula na linha
          cell1.innerHTML = array[i].soma; // na célula passa o valor 
          cell2.innerHTML = array[i].categoria; // na célula passa o valor
      }
  }
}
imprimirArray('table1', arr);
<table id="table1" border="1" width="100%">
</table>

How it works?

Search the id of <table/> and create with the command insertRow a row in your table, as seen in your code has two fields create two cells in that row with the command insertCell passing the index number of these cells. With these two cells add by the property innerHTML the value of the information being sufficient to show the values in a table.

Reference: Table insertRow() Method

Browser other questions tagged

You are not signed in. Login or sign up in order to post.