Skip to content

Instantly share code, notes, and snippets.

@TehShrike
Created January 24, 2025 03:38
Show Gist options
  • Save TehShrike/f492b0f9aab63dc8c341250e0081efc1 to your computer and use it in GitHub Desktop.
Save TehShrike/f492b0f9aab63dc8c341250e0081efc1 to your computer and use it in GitHub Desktop.
write csv
const requires_quoting_regex = /["\n,]/
const escape_quotes = (str: string) => str.replace(/"/g, `""`)
export const escape_csv_value = (str: string) => requires_quoting_regex.test(str)
? `"${ escape_quotes(str) }"`
: str
export const csv_line = (...values: string[]) => values.map(escape_csv_value).join(`,`)
export const objects_to_csv = (array: { [k: string]: string }[]) => {
const all_keys = [ ...new Set(array.map(Object.keys).flat()) ]
return [
all_keys,
...array.map(object => all_keys.map(key => object[key] || ``)),
].map(values => csv_line(...values)).join(`\n`)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment