Created
November 30, 2021 12:47
-
-
Save gitSambhal/af93683dfaec527824e43337dcfbeee3 to your computer and use it in GitHub Desktop.
HTML table from array of objects in Javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* | |
* @param {Array} arr Array of object to convert to HTML table | |
* @param {Array} takeOnly Array of keys to keep in the resulting HTML table | |
* @param {Array} blacklist Array of keys to skip in the resulting HTML table | |
* @return {String} HTML Table | |
*/ | |
export const ArrayOfObjectsToTable = function ({ arr = [], takeOnly = [], blacklist = [] }) { | |
let classes = { | |
table : 'table table-sm table-responsive table-border', | |
tr:'d-flex', | |
td: 'flex-fill' | |
} | |
let html = '' | |
let table = [] | |
arr.forEach((row, i) => { | |
let columns = Object.keys(row) | |
columns = columns.filter(col => !blacklist.includes(col)) | |
if (takeOnly.length) columns = columns.filter(col => takeOnly.includes(col)) | |
let tr = [] | |
columns.forEach(col => { | |
let td = arr[i][col] | |
tr.push(td) | |
}) | |
table.push(tr) | |
}) | |
let rowsHtml = table.map(row => { | |
let tr = row.map(col => { | |
return `<td class="${classes.td}">${col}</td>` | |
}).join('') | |
return `<tr class="${classes.tr}">${tr}</tr>` | |
}).join('') | |
html = `<table class="${classes.table}">${rowsHtml}</table>` | |
return html; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment