Created
February 12, 2019 02:34
-
-
Save stevenbeales/e2541ea9c75e1994006a0c40458e4d09 to your computer and use it in GitHub Desktop.
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 JSONtoCSV = (arr, columns, delimiter = ',') => | |
[ | |
columns.join(delimiter), | |
...arr.map(obj => | |
columns.reduce( | |
(acc, key) => `${acc}${!acc.length ? '' : delimiter}"${!obj[key] ? '' : obj[key]}"`, | |
'' | |
) | |
) | |
].join('\n'); |
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
JSONtoCSV([{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }], ['a', 'b']); // 'a,b\n"1","2"\n"3","4"\n"6",""\n"","7"' | |
JSONtoCSV([{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }], ['a', 'b'], ';'); // 'a;b\n"1";"2"\n"3";"4"\n"6";""\n"";"7"' | |
Converts an array of objects to a comma-separated values (CSV) string that contains only the columns specified. | |
Use Array.prototype.join(delimiter) to combine all the names in columns to create the first row. Use Array.prototype.map() and Array.prototype.reduce() to create a row for each object, substituting non-existent values with empty strings and only mapping values in columns. Use Array.prototype.join('\n') to combine all rows into a string. Omit the third argument, delimiter, to use a default delimiter of ,. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment