json-to-csv-export icon indicating copy to clipboard operation
json-to-csv-export copied to clipboard

Declare headers and data together

Open testerez opened this issue 2 years ago • 0 comments

Hello, I just wanted to share my way to declare headers and data which I believe is easier in most cases, especially when there is a lot of columns. Just in case it helps anyone or you are open to add something similar baked in the lib.

Basically, I declare my data like this:

const columns: CsvColumn<Person>[] = [
    {
      title: 'First Name',
      getContent: (p) => p.firstName,
    },
    {
      title: 'Last Name'
      getContent: (p) => p.lastName,
    }
  ]

This is possible thanks to this small helper:

import type csvDownload from 'json-to-csv-export'

type CsvDownloadProps = Parameters<typeof csvDownload>[0]

export type CsvColumn<T> = {
  title: string
  getContent: (value: T) => string | null | number | undefined
}

export const getCsvDownloadProps = <T>({
  columns,
  data,
  ...props
}: Omit<CsvDownloadProps, 'data' | 'headers'> & {
  columns: CsvColumn<T>[]
  data: T[]
}): CsvDownloadProps => {
  return {
    ...props,
    headers: columns.map((c) => c.title),
    data: data.map((d) => columns.map((c) => c.getContent(d) ?? '')),
  }
}

testerez avatar Oct 08 '23 11:10 testerez