CodingTrain / Suggestion-Box

A repo to track ideas for topics
570 stars 86 forks source link

Coding Challenge: Tabletop.js to HTML Table #1215

Open trevorcapozza opened 5 years ago

trevorcapozza commented 5 years ago

Could you show how to get data from an array using tabletop.js into an html table? The link below shows an image explaining what I'm trying to do as well as a link to my code.

Visual explanation

Link to my code

Thanks!

Californ1a commented 5 years ago

First thing, probably much better to make a repo instead of passing around a zip. Most people aren't going to just download random zips.

Second, you've got your tabletop init in two places, both in your html file and in setup.js (though setup isn't even being loaded, no script tag for it). You should stick with just one of those.

As for converting the tabletop data to actual rows in your table, all you need to do is give your table an ID to be able to select it, and have a loop in the tabletop callback:

function gotData(data) {
  const table = document.getElementById("table1-id");
  let tableRows = "";
  for (const player of data) {
    tableRows += "<tr>";
    const keys = Object.keys(player);
    // using a secondary loop here rather than manually typing the properties
    // just in case the table column names change in the source google sheet
    for (let i = 0; i < keys.length; i++) {
      tableRows += `<td>${player[keys[i]]}</td>`;
    }
    tableRows += "</tr>";
  }
  table.tBodies[0].innerHTML += tableRows;
}

Or if you want to do it with builtin functions without directly editing the innerHTML, like this:

function gotData(data) {
  const table = document.getElementById("table1-id").tBodies[0];
  for (const player of data) {
    const row = table.insertRow(-1); // index -1 inserts at bottom
    const keys = Object.keys(player);
    for (let i = 0; i < keys.length; i++) {
      const c = row.insertCell(i);
      c.appendChild(document.createTextNode(player[keys[i]]));
    }
  }
}