Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert HTML table to Javascript Object with jQuery

Tags:

I am trying to convert this HTML table:

enter image description here

Code:

<table id="students" border="1">     <thead>         <tr>             <th>Name</th>             <th>Age</th>             <th>Grade</th>         </tr>     </thead>     <tbody>         <tr class="student">             <td>Oscar</td>             <td>23</td>             <td>16.5</td>                 </tr>         <tr class="student">             <td>Antonio</td>             <td>32</td>             <td>14</td>                 </tr>         <tr class="student">             <td>Jessica</td>             <td>21</td>             <td>19</td>                 </tr>     </tbody> </table>​​​​​​ 

Into a javascript object using jQuery:

var tbl = $('table#students tr').map(function() {   return $(this).find('td').map(function() {     return $(this).text();   }).get(); }).get(); 

The above code will output the following array:

["Oscar", "23", "16.5", "Antonio", "32", "14", "Jessica", "21", "19"] 

Everything is good at this point but how can I do if I want the javascript objects inside the array to have the following structure:

[{id:1, name: "Oscar", age: 23, grade: 16.5}, {id:2, name: "Antonio", age: 32, grade: 14}, {id:3, name: "Jessica", age: 21, grade: 19}] 

enter image description here

Just to be more specific...

  • The id is obtained from the tr
  • The name, age and grade values are obtained from each row

I made this jsfiddle to test:

http://jsfiddle.net/oscarj24/ptVDm/

Thanks

like image 957
Oscar Jara Avatar asked Sep 05 '12 23:09

Oscar Jara


2 Answers

I needed this exact thing, except I needed more features to be able to override column names and ignore any hidden rows. I wrote a jQuery plugin that does just that, located here https://github.com/lightswitch05/table-to-json

for your example you would do: (http://jsfiddle.net/ptVDm/118/)

var table = $('#students').tableToJSON(); 

One thing to note is that the id's aren't part of the resulting object. You could just get the id from the object's array location. Or if you really needed it to be part of the object, you could create an hidden column for the ID's and then they would be included

like image 25
lightswitch05 Avatar answered Sep 22 '22 00:09

lightswitch05


var tbl = $('#students tr:has(td)').map(function(i, v) {     var $td =  $('td', this);         return {                  id: ++i,                  name: $td.eq(0).text(),                  age: $td.eq(1).text(),                  grade: $td.eq(2).text()                               } }).get(); 

like image 64
undefined Avatar answered Sep 20 '22 00:09

undefined