💾objects to HTML table
JS ⟩ value ⟩ object⟩ built-in ⟩ Array ⟩ example ⟩ objects to HTML table
turn an array of objects into a HTML <table> element.
replit ⟩ objects to HTML table, require ⟩ Node+ext
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,
};💈範例:
Last updated
Was this helpful?