Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert html table to array in javascript

Tags:

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> 
like image 579
n0minal Avatar asked Mar 06 '12 07:03

n0minal


People also ask

How to convert an HTML table to a JavaScript array?

To convert an HTML table to an array in JavaScript, we can use the spread operator and some array methods. to get all the tr elements in a node list with table. rows . Then we spread them into an array.


2 Answers

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/

like image 51
Andreas Eriksson Avatar answered Sep 23 '22 15:09

Andreas Eriksson


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 !

like image 29
Youcef Ali Avatar answered Sep 24 '22 15:09

Youcef Ali