How to convert HTML table to Javascript Object with jQuery

后端 未结 6 1067
夕颜
夕颜 2020-12-02 17:49

I am trying to convert this HTML table:

\"enter

Code:

6条回答
  •  孤城傲影
    2020-12-02 18:02

    Try below approach for n columns

    DEMO: http://jsfiddle.net/ptVDm/7/

    var tblhdr = $('table#students th').map(function () {
        return $(this).text();
    }).get();
    
    console.log(tblhdr);
    
    var tbl = $('table#students tbody tr').map(function(idx, el) {
        var td = $(el).find('td');
        var obj = {id: idx+1};
    
        //Can work on number of columns
        for (var i = 0; i < tblhdr.length; i++) {
            obj[tblhdr[i]] = td.eq(i).text();
        }
    
        return obj;
    }).get();
    
    console.log(tbl);
    

提交回复
热议问题