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.

Revisions

  1. Matt Mazzola created this gist Nov 23, 2020.
    17 changes: 17 additions & 0 deletions createCsvFromObjects.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,17 @@
    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
    }