csvdrop
Version:
./jsontocsv/README.md
43 lines (39 loc) • 1.15 kB
text/typescript
export function jsontocsv(
data: Record<string, any>[],
filename: string = "data.csv"
): void {
if (
!Array.isArray(data) ||
data.length === 0 ||
typeof data[0] !== "object" ||
Array.isArray(data[0])
) {
throw new Error("Data must be a non-empty array of objects.");
}
const headers = Object.keys(data[0]);
const csvRows = [
headers.join(","), // CSV headers
...data.map((row) =>
headers
.map((field) => {
const value = row[field];
// Escape quotes and wrap value in double quotes
return `"${String(value ?? "").replace(/"/g, '""')}"`;
})
.join(",")
),
];
const csvContent = csvRows.join("\n");
const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.setAttribute(
"download",
filename.endsWith(".csv") ? filename : filename + ".csv"
);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
}