If I have an object with data structured like this:
{ key1: 1, key2: 2, key3: 3, key4: 4, key5: 5 }
how could I (using pure JS) turn this into a table that looks like this:
(the css does not in any way have to look like this. It is simply the formatting I would like)
However, the data that would be put into the table will change, so how could I make that happen automatically?
yes it must be an object.
Thank you so much.
Things that will help:
- how to add another row/column to a table
- how to assign text value to each cell
- how to create a loop that will be able to get the key and the key value of one of the sets in the object
- if someone explained the main aspects of what this piece of code means:
function tableCreate() {
//body reference
var body = document.getElementsById("body");
// create elements <table> and a <tbody>
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
// cells creation
for (var j = 0; j <= 2; j++) {
// table row creation
var row = document.createElement("tr");
for (var i = 0; i < 2; i++) {
// create element <td> and text node
//Make text node the contents of <td> element
// put <td> at end of the table row
var cell = document.createElement("td");
var cellText = document.createTextNode("cell is row "+j+", column "+i);
cell.appendChild(cellText);
row.appendChild(cell);
}
//row added to end of table body
tblBody.appendChild(row);
}
// append the <tbody> inside the <table>
tbl.appendChild(tblBody);
// put <table> in the <body>
body.appendChild(tbl);
// tbl border attribute to
tbl.setAttribute("border", "2");
}
<div id="body"></div>
<td>at a time.