ITADN

Declare headers and data together

#55Closedtesterez 创建于 2023-10-08
T
testerezcommented
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: ```ts 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: ```ts 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) ?? '')), } } ```
关闭于 2024-10-04 2 条评论