HTML table data into arrays via jQuery

2019-04-07 06:01发布

I want to extract data from an html table like

<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>

and get arrays:

  • an array for the headers
  • a 2d array for the column values (or an array for each column)

    How can I do this using jQuery?

    I don't care to serialize it, or put it into a JSON object because I want to use it to render a chart.


    related General design question:

    at the moment I have something like

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

    does it make more sense to throw a JSON object back from the ajax query and then render a table and a chart from there?

  • 8条回答
    霸刀☆藐视天下
    2楼-- · 2019-04-07 07:01

    demo updated 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);
    
    查看更多
    聊天终结者
    3楼-- · 2019-04-07 07:04

    Something along the lines of:

    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();
        });
    });
    

    This gives you two arrays, thArray which is an array of your headings and contentArray which is a 2d array containing rows and columns: contentArray['row1']['col0'] returns " Value 1,1"

    Actually, contentArray contains the th's as well... referenced 'row0'

    查看更多
    登录 后发表回答