Print out Javascript array in table

Viewed 44596

I have this array:

var employees = [
{ "firstName":"John" , "lastName":"Doe" }, 
{ "firstName":"Anna" , "lastName":"Smith" }, 
{ "firstName":"Peter" , "lastName": "Jones" }
];

and I would like to print the entire array out as a html table. How would I accomplish this?

I tried this but could only get the final name the print:

<!DOCTYPE html>
<html>
<body>
<h2>Create Object from JSON String</h2>
<p>
First Name: <span id="fname"></span><br /> 
Last Name: <span id="lname"></span><br /> 
</p> 
<script type="text/javascript">
var txt = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';

var obj = eval ("(" + txt + ")");

for (i=0; i<txt.length; i++){
    document.getElementById("fname").innerHTML=obj.employees[i].firstName 
    document.getElementById("lname").innerHTML=obj.employees[i].lastName 
}
</script>
</body>
</html>
3 Answers
Related