Skip to content

Instantly share code, notes, and snippets.

@sators sators/arrayToCsv.js

Last active Jun 22, 2020
Embed
What would you like to do?
Convert Array of Objects to CSV with Javascript
/**
* Take an array of objects of similar structure and convert it to a CSV.
* @source https://halistechnology.com/2015/05/28/use-javascript-to-export-your-data-as-csv/
* @modifiedBy sators
* @param {Array} options.data Array of data
* @param {String} options.columnDelimiter Column separator, defaults to ","
* @param {String} options.lineDelimiter Line break, defaults to "\n"
* @return {String} CSV
*/
export default ({data = null, columnDelimiter = ",", lineDelimiter = "\n"}) => {
let result, ctr, keys
if (data === null || !data.length) {
return null
}
keys = Object.keys(data[0])
result = ""
result += keys.join(columnDelimiter)
result += lineDelimiter
data.forEach(item => {
ctr = 0
keys.forEach(key => {
if (ctr > 0) {
result += columnDelimiter
}
result += typeof item[key] === "string" && item[key].includes(columnDelimiter) ? `"${item[key]}"` : item[key]
ctr++
})
result += lineDelimiter
})
return result
}
import { expect } from "chai"
import arrayToCsv from "./arrayToCsv"
describe("arrayToCsv()", () => {
let data
beforeEach(() => {
data = [{
col1: "data1",
col2: "data2",
col3: 3
}]
})
it("converts an aray to a CSV with the default parameters", () => {
const expected = "col1,col2,col3\ndata1,data2,3\n"
expect(arrayToCsv({data})).to.equal(expected)
})
it("returns null if no data is passed", () => {
expect(arrayToCsv({})).to.equal(null)
expect(arrayToCsv({data: []})).to.equal(null)
})
it("can use a custom column delimiter", () => {
const expected = "col1:col2:col3\ndata1:data2:3\n"
expect(arrayToCsv({data, columnDelimiter: ":"})).to.equal(expected)
})
it("can use a custom line delimiter", () => {
const expected = "col1,col2,col3:data1,data2,3:"
expect(arrayToCsv({data, lineDelimiter: ":"})).to.equal(expected)
})
it("encompases the value with quotes when it contains the columnDelimiter", () => {
data[0].col2 = "data,2"
const expected = "col1,col2,col3\ndata1,\"data,2\",3\n"
expect(arrayToCsv({data})).to.equal(expected)
})
})
@select

This comment has been minimized.

Copy link

select commented Aug 13, 2018

Hey thanks for you code, I had the requirement that I needed to escape string values with quotes etc and non uniform object. Here is my code https://gist.github.com/select/0e2aa49b98ea81db7c615e6560497c41

@kevlozano

This comment has been minimized.

Copy link

kevlozano commented Apr 28, 2020

This is great code! very clean and easy to read. You pointed me in the right direction. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.