Create two-dimensional html table with js from python list

1

I would like to create a two-dimensional table, in which the x-axis is the dates (with title format) and the axis and the names of the data (also with title format).

I collect data from a JSON:

{"dataval": [ 
    {
       "date":"2014-01-01 00:00:00",
       "value":25776510,
       "name":"Nom1"
    },
    {
        "date":"2014-02-01 00:00:00",
        "value":789,
       "name":"Nom1"
    },
    {
        "date":"2014-01-01 00:00:00",
        "value":0,
        "name":"Nom2"
    },
    {
        "date":"2014-02-01 00:00:00",
        "value":0,
        "name":"Nom2"
     }
]}

I try to traverse the data and join them in a string but I can not get it.

for (var i = 0; i < data.dataval.length; i++) {
    date_now = data.dataval[i]['date'];
    name_now = data.dataval[i]['name'];

    if (i == 0){

        date = date_now;
        date_bef = date_now;
        table += "<th>" + date + "</th>";

        name = name_now;
        name_bef = name_now;
        table += "<th>" + name + "</th>";

    }else{

        date_bef = data.dataval[i-1]['date'];
        name_bef = data.dataval[i-1]['name'];

    }      

    if (date_bef != date_now){

        date = date_now;
        table += "<th>" + date + "</th>";
    }    

    if (name_bef != name_now){

        name = name_now;
        names_col += "<th>" + name + "</th>";
    }

    name = data.dataval[i]['name'];
    value = data.dataval[i]['value'];
    table += '<tr>' + value + '</tr>';


}
table +="</tr>";
table += "</table>";
$("#tbody_tabla").html(table);

I would also like to add that the final result in HTML would be:

<table style="width:100%">
  <tr>
    <th></th>
    <th>2014-01-01 00:00:00</th>        
    <th>2014-02-01 00:00:00</th>
  </tr>
  <tr>
    <th>Nom1</th>
    <td>25776510</td>       
    <td>789</td>
  </tr>
  <tr>
    <th>2014-02-01 00:00:00</th>
    <td>0</td>      
    <td>0</td>
  </tr>
</table>
    
asked by Didina Deen 06.04.2016 в 17:31
source

1 answer

1

What you want can be easily achieved with a reduce to do a double grouping of your data first by rows and then by columns.

This method is used to transform any collection into a value or another collection , in your case I am transforming the array into an object where its properties are the rows and each of these contains another object where its properties are the dates and finally these have the value of the cell.

$(function() {
  // cachear una referencia a la tabla para aumentar la eficiencia en los selectores
  var $tabla = $('#resultado').append('<thead><tr></tr></thead>');
  // insertar un header
  var $header = $tabla.find('tr');
  // agregar cabecera vacia
  $header.append('<th></th>');
  // agregar el body de la tabla
  $tabla.append('<tbody></tbody>');
  var $tbody = $tabla.find('tbody');

  // tus datos
  var data = {
    "dataval": [{
      "date": "2014-01-01 00:00:00",
      "value": 25776510,
      "name": "Nom1"
    }, {
      "date": "2014-02-01 00:00:00",
      "value": 789,
      "name": "Nom1"
    }, {
      "date": "2014-01-01 00:00:00",
      "value": 0,
      "name": "Nom2"
    }, {
      "date": "2014-02-01 00:00:00",
      "value": 0,
      "name": "Nom2"
    }]
  };

  // primero tienes que agupar todos los datos
  // se agrupa primero por nombre y luego por fecha
  var datosTabla = data.dataval.reduce(function(curr, item) {
    // si nos encontramos un item que no ha sido guardado creamos un objeto vacío
    if (!curr[item.name]) {
      curr[item.name] = {};
    }
    // creamos una propiedad con el valor de "date" para usarla al imprimir las cabeceras y le asignamos el valor correspondiente
    curr[item.name][item.date] = item.value;
    return curr;
  }, {});

  // esta variable sirve para imprimir los headers y hacer más eficiente el programa
  // básicamente los headers se imprimen en la primera iteración así que no imprimimos más si ya fueron creados
  var headers = false;

  $.each(datosTabla, function(key, item) {
    // creamos una nueva fila en el cuerpo de la tabla y la seleccionamos
    var $row = $tbody.append('<tr></tr>').last();
    // le agregamos una columna con el valor de "name"
    $row.append('<td>' + key + '</td>');
    // iteramos por todas los "dates" o columnas
    $.each(item, function(keyRow, itemRow) {
      // si no se han creados los headers los creamos en esta iteración
      if (!headers) {
        $header.append('<td>' + keyRow + '</td>');
      }
      // agregamos cada elemento de la columna
      $row.append('<td>' + itemRow + '</td>')
    });

    // indicamos que ya no es necesario volver a imprimir los headers
    headers = true;
  });

});
table#resultado {
  width: 100%;
  border: gray solid 1px;
}
table#resultado td {
  border: gray solid 1px;
  padding: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.8.2/lodash.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="resultado">
</table>
    
answered by 08.04.2016 в 20:02