Skip to content

Instantly share code, notes, and snippets.

@bhelm
Forked from JeffJacobson/tocsv.js
Last active July 4, 2019 14:26
Show Gist options
  • Save bhelm/0c3800359c73e2797e3fc545b1676aed to your computer and use it in GitHub Desktop.
Save bhelm/0c3800359c73e2797e3fc545b1676aed to your computer and use it in GitHub Desktop.
JavaScript object to CSV
/**
* Converts a value to a string appropriate for entry into a CSV table. E.g., a string value will be surrounded by quotes.
* @param {string|number|object} theValue
*/
function toCsvValue(theValue) {
let t = typeof theValue,
output
let sDelimiter = '"'
if (t === 'undefined' || t === null) {
output = ''
} else if (t === 'string') {
output = sDelimiter + theValue.replace(/"/g, '""') + sDelimiter
} else {
output = sDelimiter + String(theValue).replace(/"/g, '""') + sDelimiter
}
return output
}
/**
* Converts an array of objects (with identical schemas) into a CSV table.
* @param {Array} objArray An array of objects. Each object in the array must have the same property list.
* @param {string} cDelimiter The column delimiter. Defaults to a comma (,) if omitted.
* @return {string} The CSV equivalent of objArray.
*/
export default function toCsv(objArray, cDelimiter) {
var i,
l,
names = [],
name,
value,
obj,
row,
output = '',
n,
nl
// Initialize default parameters.
let sDelimiter = '"'
if (typeof cDelimiter === 'undefined' || cDelimiter === null) {
cDelimiter = ','
}
for (i = 0, l = objArray.length; i < l; i += 1) {
// Get the names of the properties.
obj = objArray[i]
row = ''
if (i === 0) {
// Loop through the names
for (name in obj) {
if (obj.hasOwnProperty(name)) {
names.push(name)
row += [
sDelimiter,
name.replace(/"/g, '""'),
sDelimiter,
cDelimiter,
].join('')
}
}
row = row.substring(0, row.length - 1)
output += row
}
output += '\n'
row = ''
for (n = 0, nl = names.length; n < nl; n += 1) {
name = names[n]
value = obj[name]
if (n > 0) {
row += cDelimiter
}
row += toCsvValue(value)
}
output += row
}
return output
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment