Convert html table to array in javascript

后端 未结 3 749
借酒劲吻你
借酒劲吻你 2020-11-28 09:22

How can an HTML table be converted into a JavaScript array?

Item Descript
相关标签:
3条回答
  • 2020-11-28 10:05

    Here's typescript solution:

    
    function getTableContent(table: HTMLTableElement): string[][] {
        return Array.from(table.rows).reduce((acc, row) => {
            const columns = Array.from(row.children)
                .map(column => column.textContent || '')
    
            return acc.concat(columns);
        }, [] as string[][])
    }
    
    0 讨论(0)
  • 2020-11-28 10:09

    This a function coverts an Html Table (just give the id) and it returns an array of the table :

                function table_to_array(table_id) {
                        myData = document.getElementById(table_id).rows
                        //console.log(myData)
                        my_liste = []
                        for (var i = 0; i < myData.length; i++) {
                                el = myData[i].children
                                my_el = []
                                for (var j = 0; j < el.length; j++) {
                                        my_el.push(el[j].innerText);
                                }
                                my_liste.push(my_el)
    
                        }
                        return my_liste
                }
    

    I hope it helps you !

    0 讨论(0)
  • 2020-11-28 10:15

    Here's one example of doing what you want.

    var myTableArray = [];
    
    $("table#cartGrid tr").each(function() {
        var arrayOfThisRow = [];
        var tableData = $(this).find('td');
        if (tableData.length > 0) {
            tableData.each(function() { arrayOfThisRow.push($(this).text()); });
            myTableArray.push(arrayOfThisRow);
        }
    });
    
    alert(myTableArray);
    

    You could probably expand on this, say, using the text of the TH to instead create a key-value pair for each TD.

    Since this implementation uses a multidimensional array, you can access a row and a td by doing something like this:

    myTableArray[1][3] // Fourth td of the second tablerow
    

    Edit: Here's a fiddle for your example: http://jsfiddle.net/PKB9j/1/

    0 讨论(0)
提交回复
热议问题