Skip to content

Instantly share code, notes, and snippets.

@AwesomeZaidi
Created December 1, 2022 17:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AwesomeZaidi/269c61fac1a8632b16ee781dca5e2707 to your computer and use it in GitHub Desktop.
Save AwesomeZaidi/269c61fac1a8632b16ee781dca5e2707 to your computer and use it in GitHub Desktop.
Shared Export to CSV Function
const CSV_PREFIX = 'data:text/csv;charset=utf-8,';
export const exportToCsv = (
data: { [key: string]: any }[],
prefix = CSV_PREFIX
) => {
if (data.length === 0) {
return '';
}
const keys = Object.keys(data[0]);
const result = [keys]
.concat(
data.map(row => keys.reduce((acc: any[], key) => [...acc, row[key]], []))
)
.map(row => row.map(item => `"${item ? item : ''}"`));
return result.reduce((acc, row) => acc + row.join(',') + '\n', prefix);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment