- Published on
Create a Table Using Object-Oriented Javascript
Table Component in Javascript
Table is main building block when we create web layout. In the Javascript interview, we get a problem where we have to implement something using Object-Oriented Javascript, so here I try to implement Table class.
here is the js code:
(function () {
"use strict";
// Table class
// it will create a table from JSON array
// create header from first array element i.e. Object
// Sort table based on header key
// iterate through array and insert rows
var tData = [
{ name: "Monte Falco", height: 1658, place: "Parco Foreste Casentinesi" },
{
name: "Monte Falterona",
height: 1654,
place: "Parco Foreste Casentinesi",
},
{ name: "Poggio Scali", height: 1520, place: "Parco Foreste Casentinesi" },
{ name: "Pratomagno", height: 1592, place: "Parco Foreste Casentinesi" },
{ name: "Monte Amiata", height: 1738, place: "Siena" },
];
const getCellValue = (tr, idx) =>
tr.children[idx].innerText || tr.children[idx].textContent;
const comparer = (idx, asc) => (a, b) =>
((v1, v2) =>
v1 !== "" && v2 !== "" && !isNaN(v1) && !isNaN(v2)
? v1 - v2
: v1.toString().localeCompare(v2))(
getCellValue(asc ? a : b, idx),
getCellValue(asc ? b : a, idx)
);
function Table(Data) {
this.tData = Data || [];
this.node = document.createElement("table");
Table.prototype.renderTable = function () {
this.generateTableHead(Object.keys(this.tData[0]));
this.generateTableRows(this.tData);
};
Table.prototype.generateTableHead = function (headerData) {
let thead = this.node.createTHead();
let row = thead.insertRow();
for (let key of headerData) {
let th = document.createElement("th");
let text = document.createTextNode(key);
th.appendChild(text);
th.addEventListener("click", () => {
const table = th.closest("table");
Array.from(table.querySelectorAll("tr:nth-child(n+2)"))
.sort(
comparer(
Array.from(th.parentNode.children).indexOf(th),
(this.asc = !this.asc)
)
)
.forEach((tr) => table.appendChild(tr));
});
row.appendChild(th);
}
};
Table.prototype.generateTableRows = function (rowData) {
for (let element of rowData) {
let row = this.node.insertRow();
for (let key in element) {
let cell = row.insertCell();
let text = document.createTextNode(element[key]);
cell.appendChild(text);
}
}
};
// todos...
// Searching
// Client Side Pagination
// Anyone wants to implement these functionality
// pls do comment ur code
}
document.body.onload = function () {
var table = new Table(tData);
table.renderTable();
document.getElementById("main-container").appendChild(table.node);
};
})();
here is the index.html
<!DOCTYPE html>
<html>
<head> </head>
<body>
<div id="main-container"></div>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
Next Article
Table of content