25

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>
1
  • 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. Commented Mar 6, 2012 at 7:48

5 Answers 5

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/

Sign up to request clarification or add additional context in comments.

4 Comments

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').
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.
If i want to add fields on my array as i convert the table. how can i do that?
Just use the <arrayName>.push(<object>);-syntax to add things to the array. Example: arrayOfThisRow.push("This value was added manually!");
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 !

3 Comments

how do I get only the visible lines?
@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)
@youcef-ali which formerly mean: from THEAD row get data attribute instead of TH content, while from the TDs get the content. Thank you.
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
                    });
            });
}

Comments

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[][])
}

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.