5


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.

2

3 Answers 3

6

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 += '</tr>';
 }
 html += '</table>';
 document.getElementById('container').innerHTML = html;
<div id="container">
</div>

Sign up to request clarification or add additional context in comments.

Comments

6

You can do this using forEach method , which accepts as parameter a callback provided function.

var users=[{"firstName":"John", "last Name":"Doe", "age":"46"},
 {"firstName":"James", "last Name":"Blanc", "age":"24"}]
users.forEach(function(item){
  $('tbody').append('<tr><td>'+item.firstName+'</td><td>'+item["last Name"]+'</td><td>'+item.age+'</td></tr>')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>firstName</th>
<th>last Name</th>
<th>age</th>
</tr>
</thead>
<tbody>

</tbody>
</table>

Comments

1

In your HTML put below code

<div id="myTable">

</div>

And in script put below code

var arrObj = [{"firstName":"John", "lastName":"Doe", "age":"46"},
 {"firstName":"James", "lastName":"Blanc", "age":"24"}]
 var objLength = arrObj.length;
var myvar = '<table>'+
'<tr>'+
'<th>firstName</th>'+
'<th>last Name</th>'+
'<th>age</th>'+
'</tr>';

 for(var i = 0; i < objLength; i++){
myvar += '<tr>'+
'<td>'+arrObj[i].firstName+'</td>'+
'<td>'+arrObj[i].lastName+'</tD>'+
'<td>'+arrObj[i].age+'</th>'+
'</tr>'     
 }

 myvar += '</table>';

console.log(myvar);
 document.getElementById('myTable').innerHTML = myvar;

Hope this works

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.