Skip to content

Instantly share code, notes, and snippets.

@rarous
Last active May 4, 2022 07:38
Show Gist options
  • Save rarous/882d421ce01708b01b42e3b1cc46951d to your computer and use it in GitHub Desktop.
Save rarous/882d421ce01708b01b42e3b1cc46951d to your computer and use it in GitHub Desktop.
CSV formater
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));
}
id title price
1 Foo $20
2 Bar $0
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