Skip to content

Instantly share code, notes, and snippets.

@1337ipJbP7U9mi9cdLngL3g5Napum7tWzM
Last active January 19, 2023 20:16
Show Gist options
  • Save 1337ipJbP7U9mi9cdLngL3g5Napum7tWzM/fd9b8aafbba79dc76971e892c2c82ec0 to your computer and use it in GitHub Desktop.
Save 1337ipJbP7U9mi9cdLngL3g5Napum7tWzM/fd9b8aafbba79dc76971e892c2c82ec0 to your computer and use it in GitHub Desktop.
Simple Javascript code to convert array of objects to CSV (spreadsheet) file
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>My Web Page</title>
<script src="./filesaver.js"></script>
<script>
let csv = "";
let csvHeaders = "";
const arrayOfObjects = [{column1: "1", column2: "2", column3: "3"},
{column1: 4, column2: 5, column3: 6}];
// This just get the names of the keys and sets them up as the header for the CSV
Object.keys(arrayOfObjects[0]).map((header) => {
csvHeaders += header + ", "
})
csv = csvHeaders;
arrayOfObjects.map((row) => {
csv += `\r\n ${row.column1}, ${row.column2}, ${row.column3}`
})
// removes the last comma
csvHeaders = csvHeaders.slice(0,-2)
console.log(csv);
var blob = new Blob([csv], {type: "text/plain;charset=utf-8"});
saveAs(blob, "yourcsv.csv");
</script>
</head>
<body></body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment