Last active
November 2, 2017 22:09
-
-
Save oliverbenns/d2be89a740df3936efaf40b58b9088ef to your computer and use it in GitHub Desktop.
Js to Csv
This file contains 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
// Usage: | |
// const records = [['James', '[email protected]'], ['Steve', '[email protected]']]; | |
// const titles = ['name', 'email']; | |
// generateCsv(records, titles); | |
// RFC 4180 | |
// Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in double-quotes. | |
const formatValue = value => { | |
const chars = [',', '"', '\n']; | |
const mustBeEnclosed = chars.some(c => value.includes(c)); | |
return mustBeEnclosed ? `"${value}"` : value; | |
} | |
// With an array, create a formatted csv string. | |
const createRow = rowData => { | |
if (!rowData) { | |
return ''; | |
} | |
return rowData | |
.map(col => col.toString()) | |
.map(formatValue) | |
.join(',') + '\n'; | |
}; | |
const generateCsv = (data, titles) => { | |
const meta = 'data:text/csv;charset=utf-8,'; | |
const headers = createRow(titles); | |
if (!data || data.constructor !== Array || data[0].constructor !== Array) { | |
console.warn('You must pass in nested arrays to generate csv data.'); | |
return meta + 'Error generating csv data\n'; | |
} | |
const rows = data.map(createRow); | |
return meta + headers + rows.join(''); | |
}; | |
export default generateCsv; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment