Created
November 23, 2020 03:30
-
-
Save mattmazzola/c3e11e1d100de6a26d46ad282913a7a1 to your computer and use it in GitHub Desktop.
Create CSV from Objects
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
export function createCsvFromObjects<T extends Record<string, unknown>>(os: T[]): string { | |
if (os.length == 0) { | |
throw new Error(`Cannon create CSV from empty list. Given list must not be empty.`) | |
} | |
const firstResult = os[0] | |
const keys = Object.keys(firstResult) | |
const headers = keys.join(',') | |
const rows = os.map(result => Object.values(result).join(',')) | |
const csv = `${headers} | |
${rows.join('\n')} | |
` | |
return csv | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment