Pregunta

Quiero extraer datos de una tabla HTML, como

<table>
    <tr>
        <th> Header1 </th>
        <th> Header2 </th>
        <th> Header3 </th>
    </tr>
    <tr>
        <td> Value 1,1 </td>
        <td> Value 2,1 </td>
        <td> Value 3,1 </td>
    </tr>

    ... rows ...

</table>

y obtener matrices:

  • una matriz para las cabeceras
  • una matriz 2D para los valores de columna (o una matriz para cada columna)

    ¿Cómo puedo hacer esto usando jQuery?

    No me importa a serializarlo, o lo pone en un objeto JSON porque quiero usarlo para hacer un gráfico.


    pregunta relacionada Diseño general:

    en el momento tengo algo así como

    1. ajax query returns html table
    2. use jQuery to get values from html table
    3. render chart
    

    ¿tiene más sentido para lanzar un objeto JSON vuelta de la consulta Ajax y luego hacer una tabla y un gráfico a partir de ahí?

        
  • ¿Fue útil?

    Solución

    ?

    $(function() {
    
      var headers = $("span",$("#tblVersions")).map(function() { 
        return this.innerHTML;
      }).get();
    
      var rows = $("tbody tr",$("#tblVersions")).map(function() { 
        return [$("td:eq(0) input:checkbox:checked",this).map(function() { 
          return this.innerHTML;     
        }).get()];
      }).get();
    
      alert(rows);
    });
    

    Otros consejos

    http://jsfiddle.net/ish1301/cnsnk/

    var header = Array();
    
    $("table tr th").each(function(i, v){
            header[i] = $(this).text();
    })
    
    alert(header);
    
    var data = Array();
    
    $("table tr").each(function(i, v){
        data[i] = Array();
        $(this).children('td').each(function(ii, vv){
            data[i][ii] = $(this).text();
        }); 
    })
    
    alert(data);
    

    otra forma de hacerlo

    var headers = jQuery('th').map(function(i,e) { return e.innerHTML;}).get();
    var datas = []
    jQuery.each(jQuery('tr:gt(0)'), function(i,e ) {
       datas.push(jQuery('td', e).map(function(i,e) {
                                         return e.innerHTML; 
                                      }).get()
                 );
    });
    

    Algo a lo largo de las líneas de:

    var thArray = new Array();
    var contentArray = new Array();
    
    $('th').each(function(index) {
      thArray[index] =    $(this).html();
    })
    
    
    $('tr').each(function(indexParent) {
      contentArray['row'+indexParent] = new Array();
        $(this).children().each(function(indexChild) {
          contentArray['row'+indexParent]['col'+indexChild] = $(this).html();
        });
    });
    

    Esto le da dos matrices, thArray que es una matriz de sus títulos y contentArray que es una matriz 2D que contiene filas y columnas: vuelve contentArray['row1']['col0'] "Value 1,1"

    En realidad, contiene contentArray del th así ... referenciados 'row0'

      

    ¿tiene más sentido para lanzar un objeto JSON vuelta de la consulta Ajax y luego hacer una tabla y un gráfico a partir de ahí?

    Sí, absolutamente. Volver JSON en respuesta a su petición AJAX, entonces usted puede hacer que la mesa usando algo como jQuery y utilizar los mismos datos subyacentes para generar el gráfico también.

    Estoy jugando con la misma cosa aquí, pero yo prefiero iteración a través de todas las tablas y escribir el encabezado y el cuerpo matrices en propiedades de cada mesa, así que aquí está mi modificación de la respuesta original:

    $(function() {
    $("table").each(function(){
      var $table = $(this),
          $headerCells = $("thead th", $(this)),
          $rows = $("tbody tr", $(this));
      var headers = [],
          rows = [];
    
    
    $headerCells.each(function(k,v) {
       headers[headers.length] = $(this).text();
      $table.prop("headAry", headers);
    });
    
    $rows.each(function(row,v) {
      $(this).find("td").each(function(cell,v) {
        if (typeof rows[cell] === 'undefined') rows[cell] = [];
        rows[cell][row] = $(this).text();
        $table.prop("bodAry", rows);
      });
    });
    console.log($(this).prop('headAry'));
    console.log($(this).prop('bodAry'));  
    });
    });
    

    JSbin

    Yo pensaría que tendría más sentido para obtener una copia de matriz JSON de la llamada AJAX y generar su tabla / gráfico a partir de eso. Con las plantillas jQuery esto no es difícil en absoluto.

    Esta es una modificación de la respuesta de Jerome Wagner que los usos recursiva mapas en lugar de un mapa dentro de un 'cada uno':

    http://jsbin.com/oveva3/383/edit

      var headers = $("th",$("#meme")).map(function() { 
        return this.innerHTML;
      }).get();
    
      var rows = $("tbody tr",$("#meme")).map(function() { 
        return [$("td",this).map(function() { 
          return this.innerHTML;     
        }).get()];
      }).get();
    
    Licenciado bajo: CC-BY-SA con atribución
    No afiliado a StackOverflow
    scroll top