Create header and logs dynamically based on a json

Asked

Viewed 561 times

1

Good afternoon to you... I need to create a table where the rows and columns are created dynamically. For example, consider this JSON:

{"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}

and the JS code

var table = '<div class=\'dataTables\'>';
         *      table += '<div class=\'table-responsive\'>';
         *      table += '<table id=\'tabela\' style=\'white-space: nowrap;\' cellspacing=\'0\' width=\'100%\' class=\'table table-hover table-striped table-bordered\'>';
         *      table += '<thead>';

                     //criar o cabecalho de acordo com o JSON

                table += '</thead>';
         *      table += '<tfoot><tr class=\'tr-foot\' id=\'tFoot\'></tr></tfoot>';
         *      table += '<tbody>';
         *          
         *          //criar as linhas de acordo com o json
         *          
         *      table += '</tbody>'
         *      table += '</table>';
         *      table += '</div>';
         *      table += '</div>';

I’m having more difficulty creating the columns, with their headers, because I don’t know how to read this json in order to check the amount of column and only take the "Header" to put in the table.

BS: I don’t want to leave static columns in the table.

  • Does this json have no commas among objs? Post the correct json sff, to my mind that’s 4 different jsons

  • Come on, I changed the json buddy

2 answers

2


you can go through the json keys of the first record to insert the header, after that, just insert the lines into tbody

var json = { "employees":[
  {"firstName":"John", "lastName":"Doe"},
  {"firstName":"Anna", "lastName":"Smith", "age": 23 },
  {"firstName":"Peter", "lastName":"Jones", "gender": "male"}
]}

var tabela = document.getElementById("tabela");
var tbody = tabela.querySelector("tbody");
var thead = tabela.querySelector("thead");

var props = [];
json.employees.forEach(function (employer, indice) {
  for (var prop in employer) {
    if (props.indexOf(prop) == -1) {
      props.push(prop);
    }
  }
});

if (json.employees.length > 0) {
  var cabecario = document.createElement("tr");
  props.forEach(function (prop, indice) {
    var coluna = document.createElement("th");
    coluna.textContent = prop;
    cabecario.appendChild(coluna);
  });
  thead.appendChild(cabecario);

  json.employees.forEach(function (employer, indice) {
    var linha = document.createElement("tr");
    props.forEach(function (prop, indice) {
      var coluna = document.createElement("td");
      coluna.textContent = employer[prop];
      linha.appendChild(coluna);
    });
    tbody.appendChild(linha);
  });
}
<div class='dataTables'>
  <div class='table-responsive'>
    <table id='tabela' style='white-space: nowrap;' cellspacing='0' width='100%' class='table table-hover table-striped table-bordered'>
      <thead>
      </thead>
      <tfoot>
        <tr class='tr-foot' id='tFoot'></tr>
      </tfoot>
      <tbody>
      </tbody>
    </table>
  </div>
</div>

EDIT

I made an adaptation in the code, now it will be able to assemble the table, even if the objects in the "Employees" list do not have the same structure.

  • Just to make a question, if I add in json for example the age column, this column will be created automatically also in my table ?

  • @Jetersonmirandagomes, the column will be created, but all objects within the list employees must have the same structure. if your json omits null values, then you will need to make a small adaptation.

  • @Jetersonmirandagomes, I made a change, I think the algorithm is flexible enough.

  • Ah tah I noticed, my class that generates the json is already dealt with that, Ja helped me a lot, spared me the creation of some 10 Tables of this....

0

You can also define your table and fill it using the date-* to check the name of the json index, I particularly like this practice because it is possible to refine the population function in order to put formatting,masks and other functions you wish to perform in a specific column.

var tabela = document.getElementById('minhaTabela');

var dados = [{
  nome: "Budwaiser",
  valor: 5.00
}, {
  nome: "Heineken",
  valor: 4.50
}, {
  nome: "Desperados",
  valor: 5.50
}];


function popularTabela(tabela, dados) {
  var nomes = [];
  var th = tabela.tHead.getElementsByTagName('th');

  for (var i = 0; i < th.length; i++) {
    nomes.push(th[i].getAttribute("data-nome"));
  }

  var tbody = "";
  for (var i in dados) {
    tbody += "<tr>" + td(dados[i]) + "</tr>";
  }

  function td(val) {
    var td = "";
    for (var i = 0; i < nomes.length; i++) {
      td += "<td>" + val[nomes[i]] + "</td>";
    }
    return td;
  }

  tabela.tBodies[0].innerHTML = tbody;
}

popularTabela(tabela, dados);
<table id="minhaTabela">
  <thead>
    <tr>
      <th data-nome="nome">Nome</th>
      <th data-nome="valor">Valor</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

In the first for() I caught all the data-nome which will be the columns to be filled is possible to create for example data-tipo and put values like "currency", "date" and ai in the function td you can include a switch to carry out the necessary functions.

Paragraphs 2 and 3 for() i fill the data according to json column values.

See also with data-tipo in: jsfiddle

Browser other questions tagged

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