Skip to content

Instantly share code, notes, and snippets.

@eugenius1
Last active November 9, 2020 23:46
Show Gist options
  • Save eugenius1/d324db2f4e57e65ee2239da09fed6a44 to your computer and use it in GitHub Desktop.
Save eugenius1/d324db2f4e57e65ee2239da09fed6a44 to your computer and use it in GitHub Desktop.
Object Array to CSV, with optional header & escaped comma & double-quotes
// Inspired by https://stackoverflow.com/a/11257124/5288481
// Assumes all objects have the same keys
function objArrayToCsv(objArray, header=true) {
// parse to object if not already one
let array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
let str = '';
// header row
if (header && array.length >= 1) {
let line = '';
for (var key in array[0]) {
if (line != '') {
line += ',';
}
line += key;
}
str += line + '\r\n';
}
for (var i = 0; i < array.length; i++) {
let line = '';
for (var index in array[i]) {
if (line != '') {
line += ',';
}
let field = array[i][index];
if (typeof(field) === 'string' && field.match('[,"]')) {
if (field.includes('"')) {
// " becomes ""
field = field.replace('"', '""');
}
// surround in double quotes
field = `"${field}"`;
}
line += field;
}
str += line + '\r\n';
}
return str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment