Advertisement
trentjs

Table from JSON Array

May 6th, 2022
1,088
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <!DOCTYPE html>
  2. <html>
  3. <style>
  4. body{
  5.     font-family: Arial, Helvetica, sans-serif;
  6. }
  7. table, th, td {
  8.   border:1px solid black;
  9. }
  10. </style>
  11. <body>
  12.  
  13. <h2>Table From Code</h2>
  14.  
  15. <table style="width:100%">
  16.  
  17. </table>
  18.  
  19. <script>
  20.     let tableSource = [
  21.   { name: "Monte Falco", height: 1658, place: "Parco Foreste Casentinesi" },
  22.   { name: "Monte Falterona", height: 1654, place: "Parco Foreste Casentinesi" },
  23.   { name: "Poggio Scali", height: 1520, place: "Parco Foreste Casentinesi" },
  24.   { name: "Pratomagno", height: 1592, place: "Parco Foreste Casentinesi" },
  25.   { name: "Monte Amiata", height: 1738, place: "Siena" }
  26. ];
  27.  
  28. function generateTableHead(table, data) {
  29.   let thead = table.createTHead();
  30.   let row = thead.insertRow();
  31.   for (let key of data) {
  32.     let th = document.createElement("th");
  33.     let text = document.createTextNode(key);
  34.     th.appendChild(text);
  35.     row.appendChild(th);
  36.   }
  37. }
  38.  
  39. function generateTable(table, data) {
  40.   for (let element of data) {
  41.     let row = table.insertRow();
  42.     for (key in element) {
  43.       let cell = row.insertCell();
  44.       let text = document.createTextNode(element[key]);
  45.       cell.appendChild(text);
  46.     }
  47.   }
  48. }
  49.  
  50. let table = document.querySelector("table");
  51. let data = Object.keys(tableSource[0]);
  52. generateTableHead(table, data);
  53. generateTable(table, tableSource);
  54. </script>
  55.  
  56. </body>
  57. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement