-
-
Save AwesomeZaidi/269c61fac1a8632b16ee781dca5e2707 to your computer and use it in GitHub Desktop.
Shared Export to CSV Function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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