Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Declare headers and data together #55

Open
testerez opened this issue Oct 8, 2023 · 0 comments
Open

Declare headers and data together #55

testerez opened this issue Oct 8, 2023 · 0 comments

Comments

@testerez
Copy link

testerez commented Oct 8, 2023

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 testerez changed the title Declare headers and data toguether Declare headers and data together Oct 8, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant