Skip to content

Instantly share code, notes, and snippets.

@sators
Last active January 3, 2023 18:10
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save sators/2c2578018c1aa1f7fedececc39658f17 to your computer and use it in GitHub Desktop.
Save sators/2c2578018c1aa1f7fedececc39658f17 to your computer and use it in GitHub Desktop.
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
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
Copy link

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