import {elem} from './ext/Node_ext.js';
// โญ objects to HTML table
function objectsToHTMLTable(objs, headers) {
// โญ table
return elem("table", table => {
// add header row
table.appendChild(elem('tr', headerRow => {
// add header cells
if (!headers) headers = Object.keys(objs[0]);
headers.forEach(header => {
headerRow.appendChild(elem('th', cell => {
cell.textContent = header;
}));
});
}));
// for each object, add data row
objs.forEach(item => {
table.appendChild(elem('tr', dataRow => {
// for each data row, add data cells
Object.values(item).forEach(value => {
dataRow.appendChild(elem('td', cell => {
cell.textContent = value;
}));
});
}));
});
});
}
// export
export {
objectsToHTMLTable,
};
๐็ฏไพ๏ผ
import {} from './js/ext/Node_ext.js';
import {objectsToHTMLTable} from './js/objectsToHTMLTable.js';
// sample data
const data = [
{ name: "John", age: 25, city: "New York" },
{ name: "Mike", age: 32, city: "Los Angeles" },
{ name: "Sarah", age: 128, city: "Chicago" }
];
// append the table to the body
const table = objectsToHTMLTable(data, ['Name', 'Age', 'City']);
document.body.appendChild(table);
// text align ("age" column)
table.$all('tr').forEach(row => {
row.children[1].style.textAlign = 'right';
});