Skip to content

Instantly share code, notes, and snippets.

@isurfer21
Created April 18, 2023 11:17
Show Gist options
  • Select an option

  • Save isurfer21/922aab5568923343cd82a7ea295e6785 to your computer and use it in GitHub Desktop.

Select an option

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…
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