Last active
March 9, 2017 00:43
-
-
Save pentaphobe/35a50ed65216154e045d6536783c70b8 to your computer and use it in GitHub Desktop.
CSV generator example
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
'use strict'; | |
let objToCsv = (function() { | |
let defaultOptions = { | |
showLabel: true, | |
lineBreak: '\r\n', | |
separator: ',' | |
}; | |
// escape quotes | |
let naiveFixString = str => typeof str === 'string' ? str.replace(/"/g, '\"') : ''; | |
// escape quotes and then quote | |
let quoteString = str => '"' + naiveFixString(str) + '"'; | |
/** | |
* take an array of row objects, output CSV string | |
* @param {Object[]} rowArray - list of row objects | |
* @param {string} title - the title which is displayed in the first lines of the output (default to '') | |
* @param {Object} options - options object with sane defaults (see below) | |
* @param {boolean} [options.showLabel=true] - whether to include column labels in the output | |
* @param {string} [options.lineBreak='\r\n'] - string to separate lines | |
* @returns {string} single (multiline) string CSV output | |
*/ | |
function objToCsv(rowArray, title, options) { | |
let opts = Object.assign({}, defaultOptions, options); | |
if (!rowArray || !rowArray.length) return {message: 'invalid row list', data:rowArray}; | |
if (!rowArray[0].hasOwnProperty('Cells')) return {message: 'no Cells object', data:rowArray[0]}; | |
const colNames = | |
Object.keys(rowArray.reduce( (accum, cur) => { | |
Object.keys(cur['Cells']).forEach( key => accum[key] = true ); | |
return accum; | |
}, {})).sort() | |
return (title ? opts.lineBreak + title + opts.lineBreak + opts.lineBreak: '') + | |
(opts.showLabel | |
? colNames.map(quoteString).join(opts.separator) + opts.lineBreak | |
: '' | |
) + | |
rowArray.map( row => { | |
return colNames.map( colName => quoteString(row.Cells[colName]) || '' ); | |
}).join(opts.lineBreak); | |
} | |
return objToCsv; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment