Created
October 27, 2019 12:02
-
-
Save lski/7454070fa07f91ddd1454b7a38e529b6 to your computer and use it in GitHub Desktop.
Converts a list of objects to a Markdown table
This file contains 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
export const toMarkdownTable = (keys = null) => (list) => { | |
if (list == null) throw new Error('The list needs to be an array'); | |
if (list.length === 0) return ''; | |
keys = keys || Object.keys(list[0]); | |
if (keys.length === 0) return ''; | |
headers = toMarkdownHeaders(keys); | |
body = list.map(obj => toMarkdownRow(obj, keys)).join('\n'); | |
return headers + '\n' + body; | |
}; | |
const toMarkdownHeaders = (headers) => { | |
let columnHeaders = []; | |
let underlines = []; | |
for (const header of headers) { | |
columnHeaders.push(`${header}`); | |
underlines.push(''.padEnd(header.length, '-')); | |
} | |
return `| ${columnHeaders.join(' | ')} |\n|-${underlines.join('-|-')}-|`; | |
}; | |
const toMarkdownRow = (obj, keys) => { | |
let output = []; | |
for (const key of keys) { | |
output.push(obj[key]); | |
} | |
return `| ${output.join(' | ')} |`; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment