I am trying to convert this HTML table:
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}]
Just to be more specific...
- The
id
is obtained from thetr
- The
name
,age
andgrade
values are obtained from each row
I made this jsfiddle to test:
http://jsfiddle.net/oscarj24/ptVDm/
Thanks