Sushan Niroula Sushan Niroula - 1 year ago 59
Javascript Question

Convert array of objects into HTML table with jQuery or Javascript



How can I convert the following Javascript array of object

[{"firstName":"John", "last Name":"Doe", "age":"46"},
{"firstName":"James", "last Name":"Blanc", "age":"24"}]


Into HTML table like below

<table>
<tr>
<th>firstName</th>
<th>last Name</th>
<th>age</th>
</tr>
<tr>
<td>John</td>
<td>Doe</tD>
<td>46</th>
</tr>
<tr>
<td>James</td>
<td>Blanc</tD>
<td>24</th>
</tr>
</table>


Thanks in advance.

Answer Source

Try this code:

var rows = [{"firstName":"John", "last Name":"Doe", "age":"46"},
 {"firstName":"James", "last Name":"Blanc", "age":"24"}];
 var html = '<table>';
 html += '<tr>';
 for( var j in rows[0] ) {
  html += '<th>' + j + '</th>';
 }
 html += '</tr>';
 for( var i = 0; i < rows.length; i++) {
  html += '<tr>';
  for( var j in rows[i] ) {
    html += '<td>' + rows[i][j] + '</td>';
  }
 }
 html += '</table>';
 document.getElementById('container').innerHTML = html;
<div id="container">
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download