Created
January 24, 2025 03:38
-
-
Save TehShrike/f492b0f9aab63dc8c341250e0081efc1 to your computer and use it in GitHub Desktop.
write csv
This file contains hidden or 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 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