Create header and records dynamically based on a json

1

Good afternoon ...  I need to create a table where 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 a hard time creating the columns, with the headers of them, because I do not know how to read this json in order to check the amount of column and only take the "Header" to put on the table.

obs: I do not want to leave the static columns in the table.

    
asked by anonymous 07.06.2016 / 20:14

2 answers

2

You can go through the json keys of the first record to insert the header, after that, just insert the rows in the 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 mount the table, even if the objects in the "employees" list do not have the same structure.

    
08.06.2016 / 13:30
0

You can also define your table and fill it using data- * to check the index name of json, I particularly like this practice because it is possible to refine the population function to put formatting, other functions that you want to run 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 1st%% of% I get all the for() that will be the columns to be filled you can create for example data-nome and put values like "currency", "date" and there in the data-tipo function you can include td to perform the necessary functions.

In 2 and 3% with% I fill in the data according to json's column values.

See also switch at: jsfiddle

    
08.06.2016 / 14:38