5

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
  • 3
    You iterate over the array and create DOM elements accordingly, or you use a template engine... Commented Aug 14, 2012 at 18:38
  • Why are you creating a JSON string directly in code, then eval-ing it? And if you want a table, why are you using <span> elements? Commented Aug 14, 2012 at 18:53
  • @Mike: If you're using a library, indicate it next time. Your question is meant to be useful to future readers. If there's no indication that jQuery is used in the question, then jQuery answers don't make sense. This isn't meant to be a one-time localized help for you only. StackOverflow is about creating posts that are useful to the community for years to come. Commented Aug 14, 2012 at 19:08

3 Answers 3

10

Using jQuery you can do:

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

// $.parseJSON will parse the txt (JSON) and convert it to an
// JavaScript object. After its call, it gets the employees property
// and sets it to the employees variable
var employees = $.parseJSON( txt ).employees;

var $table = $( "<table></table>" );

for ( var i = 0; i < employees.length; i++ ) {
    var emp = employees[i];
    var $line = $( "<tr></tr>" );
    $line.append( $( "<td></td>" ).html( emp.firstName ) );
    $line.append( $( "<td></td>" ).html( emp.lastName ) );
    $table.append( $line );
}

$table.appendTo( document.body );

// if you want to insert this table in a div with id attribute 
// set as "myDiv", you can do this:
$table.appendTo( $( "#myDiv" ) );

jsFiddle: http://jsfiddle.net/davidbuzatto/aDX7E/

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

1 Comment

What if you just want to iterate through an already existing table on an HTML page and write it to the bottom. How can you append the table data to the already existing web document?
10
var table = document.createElement("table");
for (var i = 0; i < employees.length; i++) {
  var row = table.insertRow(-1);
  var firstNameCell = row.insertCell(-1);
  firstNameCell.appendChild(document.createTextNode(employees[i].firstName));
  var lastNameCell = row.insertCell(-1);
  lastNameCell.appendChild(document.createTextNode(employees[i].lastName));
}
document.body.appendChild(table);

1 Comment

can I ask why you are using (-1) in table.insertRow() ? why it's (-1) ? Same for insertCell
3

A reusable JSON to table conversion solution for objects in an array type of data structure. Object properties are inserted at the header cells and the values are inserted at the data cells. Sorry for my unorthodox indenting but it makes me feel comfortable with functional programming.

var employees = [
{ "firstName":"John" , "lastName":"Doe" }, 
{ "firstName":"Anna" , "lastName":"Smith" }, 
{ "firstName":"Peter" , "lastName": "Jones" }
],
goods = [
{ "ID":"0001" , "Description":"Cool Table", "Price":"499" , "Color":"Green" }, 
{ "ID":"0002" , "Description":"Ceramic Vase", "Price":"120" , "Color":"Beige" }, 
{ "ID":"0003" , "Description":"Titanium Ashtray", "Price":"999" , "Color":"Titanium Color" },
{ "ID":"0004" , "Description":"Story Book", "Price":"1" , "Color":"Yellow" },
{ "ID":"0005" , "Description":"Chair", "Price":"120" , "Color":"Pink" }
],


tableMaker = o => {var keys = Object.keys(o[0]),
                   rowMaker = (a,t) => a.reduce((p,c,i,a) => p + (i === a.length-1 ? "<" + t + ">" + c + "</" + t + "></tr>"
                                                                                   : "<" + t + ">" + c + "</" + t + ">"),"<tr>"),
                       rows = o.reduce((r,c) => r + rowMaker(keys.reduce((v,k) => v.concat(c[k]),[]),"td"),rowMaker(keys,"th"));
                   return "<table>" + rows + "</table>";
                  };

document.write(tableMaker(employees));
document.write(tableMaker(goods));

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.