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 this jQuery code:
var tbl = $('table#students tr').map(function() {
return $(this).find('td').map(function() {
return $(this).text();
}).get();
}).get();
That outputs the following:
["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 Object to have this 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 with the above output...
- The
id
is obtained from thetr
. - The
name
,age
andgrade
attributes are from the table header.
I made this jsfiddle to test:
http://jsfiddle.net/oscarj24/ptVDm/
Thanks in advance :-)