Sushan Niroula Sushan Niroula - 1 year ago 43
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

<th>last Name</th>

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">

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