Last active
November 9, 2020 23:46
-
-
Save eugenius1/d324db2f4e57e65ee2239da09fed6a44 to your computer and use it in GitHub Desktop.
Object Array to CSV, with optional header & escaped comma & double-quotes
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
// 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