# objects to HTML table

[JS](https://lochiwei.gitbook.io/web/js) ⟩ [value](https://lochiwei.gitbook.io/web/js/val) ⟩ [object](https://lochiwei.gitbook.io/web/js/val/obj)⟩ [built-in](https://lochiwei.gitbook.io/web/js/val/builtin) ⟩ [Array](https://lochiwei.gitbook.io/web/js/val/builtin/arr) ⟩ [example](https://lochiwei.gitbook.io/web/js/val/builtin/arr/ex) ⟩ objects to HTML table

{% hint style="success" %}
turn an array of objects into a HTML \<table> element.
{% endhint %}

{% tabs %}
{% tab title="💾 程式" %}

* replit ⟩ [objects to HTML table](https://replit.com/@pegasusroe/objects-to-HTML-table#script.js),  require ⟩ [+ext](https://lochiwei.gitbook.io/web/browser/dom/type/node/+ext "mention")

```javascript
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,
};
```

💈範例：&#x20;

```javascript
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';
});
```

{% endtab %}

{% tab title="👥 相關" %}

* [dom](https://lochiwei.gitbook.io/web/browser/dom "mention")
  {% endtab %}

{% tab title="📗 參考" %}

* [ ] Eloquent JS ⟩ DOM ⟩ [Build a Table](https://eloquentjavascript.net/14_dom.html#i_g/5UC3zznV)
  {% endtab %}

{% tab title="📘 手冊" %}

* [document.createElement()](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement)
  {% endtab %}
  {% endtabs %}
