Skip to content

Instantly share code, notes, and snippets.

@thadeu
Created March 16, 2020 12:55
Show Gist options
  • Save thadeu/d02800aa42bcca89f67790068d100b13 to your computer and use it in GitHub Desktop.
Save thadeu/d02800aa42bcca89f67790068d100b13 to your computer and use it in GitHub Desktop.
Generate CSV with JS Native
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