Oscar Jara Oscar Jara - 2 months ago 17
Javascript Question

How to convert HTML table to Javascript Object with jQuery

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

Answer
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();