Build a table from your data
Give the library column definitions, row records, and optional JSON templates and table structure. It returns a JSON description of a table. A separate renderer can turn that description into browser elements.
Quick start
Install the package and pass an object containing columns and rows. The defaults create a header row and body cells.
npm install json-transformer-funcsimport { tableFromData } from "json-transformer-funcs";
const inData = {
columns: [
{ columnName: "Item" },
{ columnName: "Price" }
],
rows: [
{ item: "Notebook", price: "$4.50" },
{ item: "Pen", price: "$1.25" }
]
};
const tableTree = tableFromData({ inData });
console.log(tableTree);The returned value is plain data: a table object containing thead and tbody descriptions. It is not an HTML element.
What the inputs mean
- Columns provide the contexts used to build header cells. By default, each column needs a
columnName. - Rows provide cell values. The default builder reads each row's values in JavaScript property order and creates one cell per value.
- Templates describe the JSON tag objects used for headers, rows, and cells. Supply a custom specification with
inSpec. - Table structure describes the outer tags and attributes. Supply a custom scaffold with
inTable.
Keep each row's value order aligned with the displayed columns. The current body builder does not match row properties to column names.
Choose the output you need
Use the JSON tree directly when you want to inspect, store, or further transform the table description. To display it, pass it to a renderer that understands the project's JSON tag shape.
const tableTree = tableFromData({ inData });
// After loading a renderer such as json-to-tag:
const tableElement = window.ks.jsonToTag.buildSpecElement(tableTree);
document.querySelector("#table-host").appendChild(tableElement);The renderer is a separate step and dependency. json-transformer-funcs does not create or append DOM elements.
Current shape requirements
- A custom table scaffold needs direct
theadandtbodychildren. - The
theadneeds a first row where generated headers can be placed. - The builder fills the header and body. Other scaffold sections, such as
colgrouportfoot, are kept but not populated bytableFromData. - Template strings can contain placeholders such as
${columnName}. Matching placeholders are replaced in text and attribute values.