Created
April 18, 2023 11:17
-
-
Save isurfer21/922aab5568923343cd82a7ea295e6785 to your computer and use it in GitHub Desktop.
This function takes an array of objects as input and returns a CSV string. The keys of the first object in the input array are assumed to be the header row. If any object in the array has extra properties than others, the CSV will adjust accordingly. The updated function checks each cell value for commas, quotes, or newlines and wraps it in doub…
This file contains hidden or 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
| function convertArrayOfObjectsToCSV(data) { | |
| const arrayCopy = [...data]; | |
| const header = Object.keys(arrayCopy[0]); | |
| const csv = [ | |
| header.join(','), | |
| ...arrayCopy.map((row) => { | |
| return header.map((fieldName) => { | |
| let cellValue = row[fieldName] !== undefined ? row[fieldName] : ''; | |
| if (typeof cellValue === 'string') { | |
| cellValue = cellValue.replace(/"/g, '""'); | |
| if (cellValue.search(/("|,|\n)/g) >= 0) { | |
| cellValue = `"${cellValue}"`; | |
| } | |
| } | |
| return cellValue; | |
| }).join(','); | |
| }), | |
| ].join('\n'); | |
| return csv; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment