Skip to content

Instantly share code, notes, and snippets.

@gitSambhal
Created November 30, 2021 12:47
Show Gist options
  • Save gitSambhal/af93683dfaec527824e43337dcfbeee3 to your computer and use it in GitHub Desktop.
Save gitSambhal/af93683dfaec527824e43337dcfbeee3 to your computer and use it in GitHub Desktop.

Revisions

  1. gitSambhal created this gist Nov 30, 2021.
    45 changes: 45 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,45 @@

    /**
    *
    *
    * @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;
    }