So you have an array or object in Javascript that you wish to “save as” a CSV file? Yes, that is totally possible in modern Javascript. Let Master Coffee walk you through some simple examples – Let’s go!
CODE DOWNLOAD
I have released this under the MIT license, feel free to use it in your own project – Personal or commercial. Some form of credits will be nice though. 🙂
VIDEO TUTORIAL
1) ARRAY TO CSV
1-array.js
// (PART A) ARRAY DATA
var data = [
["Coffee", "Strength", "Description"],
["Espresso", "Strong", "Rich, chocolatey, nutty"],
["Cold Brew", "Medium-Strong", "Smooth, slightly sweet, chocolaty"],
["Latte", "Weak", "Mild coffee aroma with dominant milk"],
["Cappuccino", "Weak", "Espresso aroma balanced with steamed milk"],
["Turkish Coffee", "Strong", "Rich, intense, slightly smoky"]
];
// (PART B) FORCE DOWNLOAD AS CSV FILE
// (B1) TO BLOB & URL
var blob = new Blob([CSV.serialize(data)], {type: "text/csv"}),
url = window.URL.createObjectURL(blob);
// (B2) FORCE DOWNLOAD
var a = document.createElement("a");
a.href = url;
a.download = "demoA.csv";
a.click();
// (B3) CLEAN UP
a.remove();
window.URL.revokeObjectURL(url);
- First, your data array has to be a nested array in the format of
[[COL, COL, COL], [COL, COL, COL], ...]
- We can manually parse the array into CSV, but the easier way is to use a simple CSV library.
- (B1) Use the CSV library to parse the array into a “CSV string” –
CSV.serialize(data)
- (B1) Then, turn the “CSV string” into a binary object (BLOB) –
var blob = new Blob(...)
- (B1) Create a temporary URL for the “CSV blob”.
- (B2) To download the “CSV blob” as a file, create an anchor tag. Point the anchor tag to the “CSV blob” and click on it.
- (B3) Recommended cleanup after the file download – Remove the anchor tag and temporary URL.
- (B1) Use the CSV library to parse the array into a “CSV string” –
2) OBJECT TO CSV
2-object.js
// (PART A) OBJECT DATA
var data = {
Coffee : ["Espresso", "Cold Brew", "Latte", "Cappuccino", "Turkish Coffee"],
Strength: ["Strong", "Medium-Strong", "Weak", "Weak", "Strong"],
Description : [
"Rich, chocolatey, nutty",
"Smooth, slightly sweet, chocolaty",
"Mild coffee aroma with dominant milk",
"Espresso aroma balanced with steamed milk",
"Rich, intense, slightly smoky"
]
};
// (PART B) RESHUFFLE INTO ARRAY
// (B1) EMPTY NESTED ARRAY
var arrange = [[]];
// (B2) REARRANGE DATA
var first = true;
for (let head of Object.keys(data)) {
// (B2-1) HEADER ROW
arrange[0].push(head);
// (B2-2) FOLLOWING ROWS
for (let [row, col] of Object.entries(data[head])) {
if (first) { arrange.push([]); }
arrange[+row+1].push(col);
}
first = false;
}
// (PART C) FORCE DOWNLOAD AS CSV FILE
// (C1) TO BLOB & URL
var blob = new Blob([CSV.serialize(arrange)], {type: "text/csv"}),
url = window.URL.createObjectURL(blob);
// (C2) FORCE DOWNLOAD
var a = document.createElement("a");
a.href = url; a.download = "demoB.csv";
a.click(); a.remove();
window.URL.revokeObjectURL(url);
- Now, objects can come in all kinds of “different arrangements”. For this example, let’s assume that the data has a structure of
{ HEAD : [COL, COL, COL], HEAD : [COL, COL, COL], ... }
. - The idea here is simple, rearrange the data object into a nested array as above.
- (B1) Create an empty nested array –
arrange = [[]]
- (B2 & B2-1) Loop through the
HEAD
of the data object, insert it into the first row ofarrange
. - (B2-2) Loop through the
COL
of the respectiveHEAD
, insert intoarrange
.
- (B1) Create an empty nested array –
- Lastly, convert the
arrange
into a “CSV blob” and force download.
3) CONVERT TO CSV & UPLOAD
3-upload.js
// (PART A) ARRAY DATA
var data = [
["Coffee", "Strength", "Description"],
["Espresso", "Strong", "Rich, chocolatey, nutty"],
["Cold Brew", "Medium-Strong", "Smooth, slightly sweet, chocolaty"],
["Latte", "Weak", "Mild coffee aroma with dominant milk"],
["Cappuccino", "Weak", "Espresso aroma balanced with steamed milk"],
["Turkish Coffee", "Strong", "Rich, intense, slightly smoky"]
];
// (PART B) UPLOAD AS CSV FILE
var form = new FormData();
form.append("csv", new Blob([CSV.serialize(data)], {type: "text/csv"}));
fetch("3-upload.php", {
method: "POST",
body: form
})
.then(res => res.text())
.then(res => console.log(res));
3-upload.js
<?php
move_uploaded_file(
$_FILES["csv"]["tmp_name"],
"demoC.csv"
);
echo "OK";
If you want to upload the generate CSV file to the server –
- Create a
var form = new FormData()
object. - Append the “CSV blob” to the form object –
form.append("csv", new Blob([CSV.serialize(data)], {type: "text/csv"}))
- Upload it to the server using
fetch()
. - Just as it as a “regular file upload” on the server-side.
THE END – CSV TO ARRAY OBJECT
That’s all for this quick tutorial and examples. Yes, we can also do the opposite of reading the CSV file, and turn it into an array/object – Check out my other tutorial on “CSV to array/object/JSON”.
CHEAT SHEET