I am trying to convert this HTML table:

Code:
The following should work:
var cols = [];
var result = [];
$('#students>thead>th').each(function(){
cols.push($(this).text().toLowerCase());
});
$('#students>tbody>tr').each(function(id){
var row = {'id': id+1};
$(this).find('td').each(function(index){
row[cols[index]] = $(this).text();
});
result.push(row);
});
console.log(result);
Basically, I find the object properties from the table head, next I create an object for each row, assigning values to property names as deduced from the earlier array.
Some obvious flaws:
colspan attribute in the table, this system won't automatically replicate the same value in different object properties, but rather limit to setting up to the remaining s.
Seeing Josiah's approach, it's probably faster than mine since mine tries to be smarter by finding property names. I would recommend his technique if you know for sure your table structure will not change. Otherwise, you would need something on the lines of my code.
Oh, and for the sake of completeness, here's a JSFiddle with mine.
- 热议问题