Skip to content

Instantly share code, notes, and snippets.

@bhaireshm
Created March 28, 2022 07:34
Show Gist options
  • Save bhaireshm/5fc702bcb213a351773c47af32b2267f to your computer and use it in GitHub Desktop.
Save bhaireshm/5fc702bcb213a351773c47af32b2267f to your computer and use it in GitHub Desktop.
Creates table with custom data using JavaScript.
/**
* Creates table with custom data.
*
* @param {Object} tableData
* @param {Object[]} tableData.data - Array of objects
* @param {String[]} tableData.fields - Fields to be shown
* @param {String[]} tableData.fieldTitles - Field Names
* @param {Object} tableData.tableProps - Field Names
* @param {String} tableData.tableProps.id - Table id
* @param {String[]} tableData.tableProps.classList - Table custom class list
* @param {String[]} tableData.tableProps.style - Table custom styles
* @returns [object HTMLArrayElement]
*/
function createTable(tableData) {
const { data = [], fields = [], fieldTitles = [], tableProps = {} } = tableData;
const tbl = document.createElement("table");
tbl.id = tableProps.id || "generic-table";
tbl.classList = tableProps.classList || "";
tbl.style = tableProps.style;
tbl.style.width = "100%"; // If not required remove.
const thead = document.createElement("thead");
const thr = document.createElement("tr");
fieldTitles.forEach((fieldTitle) => {
const th = document.createElement("th");
th.style = "";
th.appendChild(document.createTextNode(fieldTitle));
thr.appendChild(th);
});
thead.appendChild(thr);
tbl.appendChild(thead);
const tbdy = document.createElement("tbody");
if (data.length > 0) {
data.forEach((object) => {
const tr = document.createElement("tr");
fields.forEach((field) => {
const td = document.createElement("td");
td.appendChild(document.createTextNode(object[field]));
tr.appendChild(td);
});
tbdy.appendChild(tr);
});
} else {
const tr = document.createElement("tr");
tr.style.textAlign = "center";
const td = document.createElement("td");
td.innerText = "No data found";
tr.appendChild(td);
tbdy.appendChild(tr);
}
tbl.appendChild(tbdy);
return tbl;
}
@bhaireshm
Copy link
Author

ez.js is more than just a library; it's a coding companion that simplifies complex tasks. Whether you're dealing with arrays, numbers, objects, or strings, ez.js has got your back! Say goodbye to coding hassles and hello to streamlined JavaScript magic.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment