Reputation: 129
I m using report generator, so my data is following a format
[{1:20,2:30,3:40},{1:50,2:10,3:80},{1:70,2:30,3:60}]
hear 1,2,3... are keys and 20,30,40,... value so this data send frontend side and display in the table.
table format like
1 | 2 | 3
-----------
20| 30| 40
-----------
50| 10| 80
-----------
70| 30| 60
-----------
Hear 1,2,3,.. are table head() and other is data()
so how to show data this format.
HTML
<table id="example"style="width:100%">
<thead>
<tr id = 'title'></tr>
</thead>
<tbody>
<tr id = 'data'></tr>
</tbody>
</table>
JavaScript Code
$("#title").html('');
$("#data").html('');
$.each(data, function (key, value) {
$.each(value, function (key, value) {
$("#title").append('<th>'+ key +'</th>');
});
});
$.each(data, function (key, value) {
$.each(value, function (key, value) {
$("#data").append('<td>'+ value +'</td>');
});
});
Upvotes: 2
Views: 2299
Reputation: 1320
solution :
$(document).ready(function()
{
var data =[{1:20,2:30,3:40},{1:50,2:10,3:80},{1:70,2:30,3:60}];
console.log(data);
var th_data = 0;
$.each(data, function(index, value1) {
var tr_str1 = '';
var tr_str2 = '';
$.each(value1,function(key,value)
{
if(th_data == 0)
{
tr_str1 = tr_str1+"<th>"+key+"</th>";
tr_str2 = tr_str2+"<td>"+value+"</td>";
}
else
{
tr_str1 = tr_str1+"<td>"+value+"</td>";
}
});
th_data = th_data + 1;
if(th_data == 1)
{
$('table').append("<tr>"+tr_str1+"</tr>"+"<tr>"+tr_str2+"</tr>");
}
else
{
$('table').append("<tr>"+tr_str1+"</tr>");
}
});
});
Upvotes: 3