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...
id
is obtained from the tr
name
, age
and grade
values are obtained from each rowI made this jsfiddle to test:
http://jsfiddle.net/oscarj24/ptVDm/
Thanks
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
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();
→
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With