Skip to content

Instantly share code, notes, and snippets.

@paulroth3d
Created May 17, 2022 19:29
Show Gist options
  • Save paulroth3d/1aaef453802f749fb1ae5b90478e1fa5 to your computer and use it in GitHub Desktop.
Save paulroth3d/1aaef453802f749fb1ae5b90478e1fa5 to your computer and use it in GitHub Desktop.

Very simple snippet to export a set of objects, into:

  • an array of values
  • tsv
  • html table
/**
* Determine a list of header fields from a collection of objects.
* @param {Object[]} objectCollection - collection of objects to create the table from.
* @return {String[]} - list of headers to include
**/
table_headersFromObject = (objectCollection) => {
const cleanCollection = (objectCollection || []).filter(r => r);
const headerSet = new Set();
for (const obj of cleanCollection) {
if (obj) {
Object.keys(obj).map((key) => headerSet.add(key));
}
}
return Array.from(headerSet);
}
table_printRow = (headerArray) => {
return (headerArray || []).join('\t');
}
table_arrayFromObject = (objectCollection, headers = null) => {
const cleanHeaders = headers === null
? table_headersFromObject(objectCollection)
: headers;
const results = [];
(objectCollection || []).forEach((obj) => {
const cleanObj = obj || {};
results.push(cleanHeaders.map((field) => obj[field]));
});
return results;
};
table_tsv = (valueArray, headers) => ([headers, ...valueArray])
.map(table_printRow)
.join('\n');
table_tsvFromObjects = (objectCollection, headers) => {
const cleanHeaders = headers || table_headersFromObject(objectCollection);
const valueArray = table_arrayFromObject(objectCollection, cleanHeaders);
return table_tsv(valueArray, cleanHeaders);
};
table_htmlHeaders = (headers) => `<tr>${headers.map(h => `<th>${h}</th>`)}</tr>`;
table_htmlValueRow = (valueArray) => `<tr>${valueArray.map(v => `<td>${v}</td>`)}</tr>`;
table_htmlValues = (valueArray) => valueArray.map(table_htmlValueRow);
table_html = (valueArray, headers) => `<table>${table_htmlHeaders(headers)}${table_htmlValues(valueArray)}</table>`;
table_htmlFromObjects = (objectCollection, headers) => {
const cleanHeaders = headers || table_headersFromObject(objectCollection);
const valueArray = table_arrayFromObject(objectCollection, cleanHeaders);
return table_html(valueArray, cleanHeaders);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment