I have an array of arrays, which looks something like this:
rows = [
[Name, Description, Number ...],
["A thing", "Description, but it has commas in it", 6, ...],
...
]
I am trying to download this as a csv file. Here's the code I have so far:
// Make a csv from rows
let csv = rows.map(row => row.join(",")).join("\n");
document.getElementById("csv_download").setAttribute("download", "file_name.csv");
document.getElementById("csv_download").href = "data:text/csv;charset=utf-8," + encodeURIComponent(csv);
This works fine when there are no commas inside the array, but right now it sees the comma after "Description" and splits it there. I also can't split it by ", because some of the items are numbers.
How do I go about solving this?
How do I go about solving this?
It varies. CSV is not a fully standardized format. But it will involve escaping those commas in the data in some way.
The most common way is to surround the fields that have commas with double quotes. If the data also has double quotes in it, you "escape" them with another double quote.
Applying that to your code:
let csv = rows.map(
row => row.map(
col => typeof col !== "string" ? col : `"${col.replace(/"/g, '""')}"`
).join(",")
).join("\n");
const rows = [
["Name", "Description", "Number"],
["A thing", "Description, but it has \"commas\" in it", 6],
];
let csv = rows.map(
row => row.map(
col => typeof col !== "string" ? col : `"${col.replace(/"/g, '""')}"`
).join(",")
).join("\n");
console.log(csv);
But again, that's just one way to handle it.