Reputation: 1141
I'm actually using this method, but it only returns me an array of arrays of values, I need a way to set a key and value, setting each key to <td>
name property would be fine.
If you have any solution in mind, please share.
HTML:
<table id="mytable">
<tr>
<td name="name">Juan</td>
<td name="age">23</td>
<td name="random">1990</td>
</tr>
<tr>
<td name="name">Jonhatan</td>
<td name="age">25</td>
<td name="random">1980</td>
</tr>
<tr>
<td name="name">Pete</td>
<td name="age">20</td>
<td name="random">1991</td>
</tr>
Javascript:
$(document).ready(function(){
$('#output').html('OUTPUT: '+tableToJson('#mytable'));
});
function tableToJson(table){
var AoA = $(table+' tr').map(function(){
return [
$('td',this).map(function(){
return $(this).text();
}).get()
];
}).get();
return JSON.stringify(AoA);
}
Current output:
[["Juan","23","1990"],["Jonhatan","25","1980"],["Pete","20","1991"]]
Output needed:
[
[{'name':"Juan"},{'age':"23"},{'random':"1990"}],
[{'name':"Jonhatan",{'age':"25"},{'random':"1980"}],
[{'name':"Pete"},{'age':"20"},{'random':"1991"}]
]
JsFiddle:
http://jsfiddle.net/j4x7pr2w/1/
Upvotes: 1
Views: 266
Reputation: 24638
The following code should fix it. It's basically an outer .each()
with an inner .map()
.
$(function() {
var AoA = [];
$('#mytable').find('tr').each(function(i,tr) {
var BoB = $(tr).find('td').map(function(j,td) {
var thisTD = {};
thisTD[ $(td).attr('name') ] = $(td).html();
return thisTD;
}).get();
AoA.push( BoB );
});
$('body').append( JSON.stringify( AoA ) );
});
Upvotes: 1
Reputation: 198436
function tableToJson(table){
var AoA = $(table).find('tr').map(function(){
var result = {};
$('td',this).each(function(){
var $this = $(this);
result[$this.attr('name')] = $this.text();
});
return result;
}).get();
return JSON.stringify(AoA);
}
Upvotes: 1