Created
March 16, 2020 12:55
-
-
Save thadeu/d02800aa42bcca89f67790068d100b13 to your computer and use it in GitHub Desktop.
Generate CSV with JS Native
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
export default function Csv() {} | |
Csv.parse = function(data) {} | |
Csv.compose = function(data) { | |
let values = [] | |
let header = Object.keys(data[0]) | |
let csv = header.join(',') | |
// each object values | |
data.map(row => values.push(Object.values(row))) | |
// create rows by multi-dimensinal array | |
values.forEach(line => { | |
csv += '\n' | |
csv += line.join(',') | |
}) | |
return csv | |
} | |
/** | |
* const data = [ | |
* { header1: 1, header2: 2}, | |
* { header1: 3, header2: 4}, | |
* ] | |
* Csv.generate(data) | |
*/ | |
Csv.generate = function(data) { | |
if (!Array.isArray(data)) { | |
throw new Error(`Csv generate should be receive array with inside objects`) | |
} | |
const cache = Csv.compose(data) | |
return new Blob([cache], { type: 'text/csv', endings: 'native' }) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment