Skip to content

Instantly share code, notes, and snippets.

@mattmazzola
Created November 23, 2020 03:30
Show Gist options
  • Save mattmazzola/c3e11e1d100de6a26d46ad282913a7a1 to your computer and use it in GitHub Desktop.
Save mattmazzola/c3e11e1d100de6a26d46ad282913a7a1 to your computer and use it in GitHub Desktop.
Create CSV from Objects
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