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, };
💈範例:
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'; });
DOM
Eloquent JS ⟩ DOM ⟩ Build a Table
document.createElement()
Last updated 1 year ago