Created
May 2, 2024 09:37
-
-
Save upalexgill/5aec3fd560f9915eaac45e262bd84a96 to your computer and use it in GitHub Desktop.
Convert array-of-objects to 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
| // array-of-objects | |
| const dataset = [ | |
| { | |
| id: 1, | |
| name: 'Foo', | |
| timestamp: new Date() | |
| }, | |
| { | |
| id: 2, | |
| name: 'Bar', | |
| timestamp: new Date() | |
| }, | |
| { | |
| id: 3, | |
| name: 'Baz', | |
| timestamp: new Date() | |
| } | |
| ]; | |
| const fields = Object.keys(dataset); | |
| const replacer = function (key, value) { return value === null ? '' : value; }; | |
| let csv = dataset.map((row) => fields.map((fieldName) => JSON.stringify(row[fieldName], replacer)).join(',')); | |
| csv.unshift(fields.join(',')); // add header column | |
| csv = csv.join('\r\n'); | |
| // Dependency on D3.js or use alternative CSV parser. | |
| console.log(d3.csvParse(csv)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment