Wheeze
Wheeze

Reputation: 65

Populate an HTML table from javascript array

I have a script array along the lines of:

var lakeData = [
{
   "Month": "1959-01",
   "LakeErieLevels": 12.296
 },
 {
   "Month": "1959-02",
   "LakeErieLevels": 13.131
 },
 {
   "Month": "1959-03",
   "LakeErieLevels": 13.966
 },
 {
   "Month": "1959-04",
   "LakeErieLevels": 15.028
 },
 {
   "Month": "1959-05",
   "LakeErieLevels": 15.844
 },
 {
   "Month": "1959-06",
   "LakeErieLevels": 15.769
 }
 ];

And I a little HTML code:

<table id="lake">
  <thead><tr><th>Date</th><th>Depth</th></tr></thead>
  <tbody></tbody>
</table>

And I'm trying to get the array to populate into the table when the page loads.

Upvotes: 3

Views: 5545

Answers (1)

user3589620
user3589620

Reputation:

var lakeData = [{
    "Month": "1959-01",
    "LakeErieLevels": 12.296
  },
  {
    "Month": "1959-02",
    "LakeErieLevels": 13.131
  },
  {
    "Month": "1959-03",
    "LakeErieLevels": 13.966
  },
  {
    "Month": "1959-04",
    "LakeErieLevels": 15.028
  },
  {
    "Month": "1959-05",
    "LakeErieLevels": 15.844
  },
  {
    "Month": "1959-06",
    "LakeErieLevels": 15.769
  }
];

function addDataToTbody(nl, data) { // nl -> NodeList, data -> array with objects
  data.forEach((d, i) => {
    var tr = nl.insertRow(i);
    Object.keys(d).forEach((k, j) => { // Keys from object represent th.innerHTML
      var cell = tr.insertCell(j);
      cell.innerHTML = d[k]; // Assign object values to cells   
    });
    nl.appendChild(tr);
  })
}

var lakeTbody = document.querySelector("#lake tbody");

addDataToTbody(lakeTbody, lakeData);
<table id="lake">
  <thead>
    <tr>
      <th>Date</th>
      <th>Depth</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>

Upvotes: 6

Related Questions