Skip to content

Instantly share code, notes, and snippets.

@isurfer21
Created October 31, 2021 17:21
Show Gist options
  • Save isurfer21/55242b65de0cf7cb55cee2f522902f77 to your computer and use it in GitHub Desktop.
Save isurfer21/55242b65de0cf7cb55cee2f522902f77 to your computer and use it in GitHub Desktop.
Tabulate the array of objects to render as HTML table
class Tabulator {
constructor(container) {
this.container = $(container);
}
setColumnHeader(columns) {
this.columns = columns;
}
toTable(data) {
let table = [];
for (let i = 0; i < data.length; i++) {
if (i == 0) {
let row = [];
for (let k in data[i]) {
row.push(this.columns[k]);
}
table.push(row);
}
let row = [];
for (let j in data[i]) {
row.push(data[i][j]);
}
table.push(row);
}
return table;
}
render(data) {
let cols,
rows = [];
for (let i = 0; i < data.length; i++) {
if (i == 0) {
let col = [];
for (let j = 0; j < data[i].length; j++) {
let cell = `<td>${data[i][j]}</td>`;
col.push(cell);
}
cols = `<tr>${col.join('')}</tr>`;
} else {
let row = [];
for (let j = 0; j < data[i].length; j++) {
let cell = `<td>${data[i][j]}</td>`;
row.push(cell);
}
rows.push(`<tr>${row.join('')}</tr>`);
}
}
let output = `<table><thead>${cols}</thead><tbody>${rows.join('')}</tbody></table>`;
this.container.html(output);
}
directRender(data) {
let cols,
rows = [];
for (let i = 0; i < data.length; i++) {
if (i == 0) {
let col = [];
for (let j in data[i]) {
if (Object.keys(this.columns).indexOf(j) >= 0) {
let cell = `<th>${this.columns[j]}</th>`;
col.push(cell);
}
}
cols = `<tr>${col.join('')}</tr>`;
}
let row = [];
for (let j in data[i]) {
if (Object.keys(this.columns).indexOf(j) >= 0) {
let cell = `<td>${data[i][j]}</td>`;
row.push(cell);
}
}
rows.push(`<tr>${row.join('')}</tr>`);
}
let output = `<table class="fl-table">
<thead>${cols}</thead>
<tbody>${rows.join('')}</tbody>
</table>`;
this.container.html(output);
}
}
/*
let tabulator = new Tabulator('#tbl');
tabulator.setColumnHeader({
host: 'Host',
port: 'Port',
status: 'Status',
});
// tabulator.render(tabulator.toTable(tbl_data));
tabulator.directRender(tbl_data);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment