Issue
Possibly a stupid question here. I have some tabular data (can be from a .csv file, but not necessarily) that I would like to output on a webpage. Ideally, I also want to preprocess that data and do some aggregation first.
Say, on my index.html file I have the following tag:
<table id="data"></table>
While my script.js file looks like this:
let my_data = {
"Fruit": ["apple","peach","banana"],
"Price": [2,3,2]
}
I thought that populating the html table with that data would be as simple as:
document.getElementById("data").innerHTML = my_data
But it's obviously more complicated than that, according to some similar posts that I could find.
Where things get trickier, is that the tabular data on the script.js side will vary in its number of rows and columns, as I intend to do some data preprocessing.
I have considered the following libraries to help me with that:
For instance, Arquero features a .toHTML()
method, and I thought that I would just have to create a pair of <div></div>
blocks and throw the Arquero table between them. But nope, won't work.
I'm considering using Plotly's table for that, but I'm wondering if there's an easy way to populate an HTML table with some data from my .js script, bearing in mind that this data will not necessarily have the same shape (which means I can prepopulate the table on the HTML side).
Is it possible to output an Arquero / Tidy.js / Data-Forge table object into an HTML element, like div or figure, etc..?
I hope it makes sense :)
Thanks!
Solution
<!-- (A) ALL WE NEED IS A <DIV> CONTAINER -->
<div id="data"></div>
<script>
// (B) DUMMY ARRAY
var my_data = ["doge", "cate", "birb", "doggo", "moon moon", "awkward seal"];
// (C) CREATE HTML TABLE
// (C1) HTML TABLE ELEMENT
var myTable = document.createElement("table"),
row = myTable.insertRow(), cell;
// (C2) LOOP THROUGH ARRAY & GENERATE ROWS-CELLS
var perrow = 2; // 2 CELLS PER ROW
my_data.forEach((value, i) => {
// ADD CELL
cell = row.insertCell();
cell.innerHTML = value;
// CLICK ON CELL TO DO SOMETHING
// cell.onclick = FUNCTION;
// TO PASS IN A RUNNING NUMBER OR PARAMETER
// cell.onclick = () => { console.log(i); };
// BREAK INTO NEXT ROW
var next = i + 1;
if (next%perrow==0 && next!=my_data.length) { row = myTable.insertRow(); }
});
// (D) ATTACH TABLE TO CONTAINER
document.getElementById("data").appendChild(myTable);
Answered By - ITC ADU
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.