0

I want to dynamically create a table from javascript and this code works fine. Is there any other method to optimize the following code?

<!DOCTYPE html>
<html>
<style>
table,th,td {
  border : 1px solid black;
  border-collapse: collapse;
}
th,td {
  padding: 5px;
}
</style>
<head>
    <title></title>
</head>
<script src="expt1.js" ></script>
<body>
<button onclick="myFunction()">Show</button>
<table id="demo"></table>
</body>
</html>

JavaScript

var myFunction = function() {
        var emp = '[{ "firstName": "John", "lastName": "Smith" }, { "firstName": "Peter", "lastName": "Jason" }, { "firstName": "Alice", "lastName": "Ray" }]';
            var obj = JSON.parse(emp);
            var table = "<tr><th>firstName</th><th>lastName</th></tr>";
           for (var i = 0; i < obj.length; i++) {
                table += "<tr><td>" + obj[i].firstName + "</td><td>" +
                obj[i].lastName + "</td></tr>";
            }
            document.getElementById("demo").innerHTML = table;
        }
  • refer this answers http://stackoverflow.com/questions/5180382/convert-json-data-to-a-html-table – Aravind Sivam Feb 26 '16 at 06:40
  • If this is working code that you want suggestions for improvement, then perhaps you should post it at http://codereview.stackexchange.com and follow their posting rules. – jfriend00 Feb 26 '16 at 06:40
  • Oh thanku..!! I would rather post there. –  Maria Feb 26 '16 at 06:43
  • If you are looking for an alternate solution, read these articles . https://teamtreehouse.com/community/html-table-from-json-store-using-pure-javascript-no-jquery and refer this plugin http://www.dynatable.com/ . – Kiran Krishnan Feb 26 '16 at 06:58
  • Possible duplicate of [Unable to render an array into table after splice and unshift in Javascript](https://stackoverflow.com/questions/23173003/unable-to-render-an-array-into-table-after-splice-and-unshift-in-javascript) – Paul Sweatte Jul 11 '17 at 01:59

0 Answers0