Last active
May 4, 2022 07:38
-
-
Save rarous/882d421ce01708b01b42e3b1cc46951d to your computer and use it in GitHub Desktop.
CSV formater
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
const reorderFields = headers => row => headers.map(key => row[key]); | |
const rowFormatter = row => | |
row.map(v => `"${String(v).replaceAll(`"`, `""`)}"`).join(","); | |
const arrayToCsv = data => data.map(rowFormatter).join("\r\n"); | |
export function writeToString(rows, options) { | |
const { headers, transform = x => x } = options; | |
const data = rows.map(transform).map(reorderFields(headers)); | |
return arrayToCsv([headers].concat(data)); | |
} |
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
id | title | price | |
---|---|---|---|
1 | Foo | $20 | |
2 | Bar | $0 |
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 { writeToString } from "./csv-formatter.mjs"; | |
const headers = ["id", "title", "price"]; | |
const transform = x => Object.assign({}, x, { price: x.price ?? "$0" }); | |
const dataset = [ | |
{ title: "Foo", id: 1, price: "$20" }, | |
{ price: null, title: "Bar", id: 2 }, | |
]; | |
console.log(writeToString(dataset, { headers, transform })); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment