Skip to content

Instantly share code, notes, and snippets.

@upalexgill
Created May 2, 2024 09:37
Show Gist options
  • Select an option

  • Save upalexgill/5aec3fd560f9915eaac45e262bd84a96 to your computer and use it in GitHub Desktop.

Select an option

Save upalexgill/5aec3fd560f9915eaac45e262bd84a96 to your computer and use it in GitHub Desktop.
Convert array-of-objects to CSV
// 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