24

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

<table id="cartGrid">
  <thead>
       <tr>
          <th>Item Description</th>
          <th>Qty</th>
          <th>Unit Price</th>
          <th>Ext Price</th>
       </tr>
  </thead>
<tbody>
    <tr><td>Old Lamp</td><td>1</td><td>107.00</td><td>107.00</td>
    <tr><td>Blue POst</td><td>2</td><td>7.00</td><td>14.00</td>
</tbody>
</table>
Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
n0minal
  • 3,195
  • 9
  • 46
  • 71
  • 2
    Sure it is. Where exactly do you have problems in implementing this? Just read the table row by row and cell by cell and add the contents to an array. – Sirko Mar 06 '12 at 07:48

5 Answers5

57

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/

Andreas Eriksson
  • 8,979
  • 8
  • 47
  • 65
  • 1
    You will want to be more specific with your selector than "table tr", especially if you are using tables for layout anywhere, as this will find all of the tr's (possibly inside other, nested tables) which are inside a table. Given the updated HTML, the selector would be `$('#cartGrid')`. – GregL Mar 06 '12 at 07:58
  • Yeah, I know that. But it seems like the OP wasn't too confident with JS and jQuery, which is fine, but I wanted to point it out in case they just copy-pasted your code and got totally unexpected results if they happened to be using nested tables for layout. – GregL Mar 06 '12 at 08:12
  • If i want to add fields on my array as i convert the table. how can i do that? – n0minal Mar 06 '12 at 08:13
  • Just use the `.push();`-syntax to add things to the array. Example: `arrayOfThisRow.push("This value was added manually!");` – Andreas Eriksson Mar 06 '12 at 11:58
6

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 !

Youcef Ali
  • 189
  • 1
  • 6
  • how do I get only the visible lines? – Fragosojp Apr 07 '21 at 17:07
  • @youcef-ali this is really good as it is vanilla javascript and works. Though can you kindly suggest how to manage to have data attribute on the first row TH elements? I mean, the THEAD row , for the user in the TH elements I'd like to show nice strings, while (then) in the same THs I'd like to set data attributes in such a manner to build an array that (as final goal) goes POST to some PHP for mysql UPDATE. Thank you for hints and tips (mean that in my idea , the data attribute will store the DB column real name) – Robert May 28 '21 at 08:28
  • @youcef-ali which formerly mean: from THEAD row get data attribute instead of TH content, while from the TDs get the content. Thank you. – Robert May 28 '21 at 08:37
2

You can write also with key value pair. this is so simple.

function htmlTableDataToArrayOfObject(){

    var arrayOfThisRow = [];
            $("#cartGrid tbody tr").each(function() {
                
                debugger;
                var description = $(this).find('td:eq(0)').text();
                var qty = $(this).find('td:eq(1)').text();
                var unitPrice= $(this).find('td:eq(2)').text();
    
                arrayOfThisRow.push({
                         desc: description,
                         quantity: qty,
                         price: unitPrice
                    });
            });
}
0

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[][])
}
cuddlemeister
  • 1,586
  • 12
  • 15
0

one easy and fast way is to map table like this:

var table = Array.prototype.map.call(document.querySelectorAll('#filter_table tr'), function(tr){
    return Array.prototype.map.call(tr.querySelectorAll('td'), function(td){
        return td.innerHTML;
    });
});
Saghachi
  • 851
  • 11
  • 19