How to convert HTML table to Javascript Object with jQuery

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

I am trying to convert this HTML table:

\"enter

Code:

6条回答
  •  悲&欢浪女
    2020-12-02 18:13

    The following should work:

    var cols = [];
    var result = [];
    $('#students>thead>th').each(function(){
        cols.push($(this).text().toLowerCase());
    });
    $('#students>tbody>tr').each(function(id){
        var row = {'id': id+1};
        $(this).find('td').each(function(index){
            row[cols[index]] = $(this).text();
        });
        result.push(row);
    });
    
    console.log(result);
    

    Basically, I find the object properties from the table head, next I create an object for each row, assigning values to property names as deduced from the earlier array.

    Some obvious flaws:

    • If the table data actually differs for some reason, (eg; empty rows for cosmetic), this system will put empty objects in the resulting array.
    • If you use colspan attribute in the table, this system won't automatically replicate the same value in different object properties, but rather limit to setting up to the remaining s.

    Seeing Josiah's approach, it's probably faster than mine since mine tries to be smarter by finding property names. I would recommend his technique if you know for sure your table structure will not change. Otherwise, you would need something on the lines of my code.

    Oh, and for the sake of completeness, here's a JSFiddle with mine.

提交回复
热议问题