-
-
Save chaituckr/674eaf45b291bae0ff7fc2e019c6c5f8 to your computer and use it in GitHub Desktop.
Convert Array of Objects to CSV with Javascript
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
/** | |
* 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 | |
} |
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
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) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment