diff --git a/src/utils/download-csv.ts b/src/utils/download-csv.ts index 492cf2d..e2b54e2 100644 --- a/src/utils/download-csv.ts +++ b/src/utils/download-csv.ts @@ -2,52 +2,24 @@ import { MapItem } from "../models/item.interface"; export const downloadMapItemsCSV = (data: MapItem[], fileName: string) => () => { - const csvValues = [ - [ - "Name", - "Rating", - "ReviewCount", - "Phone", - "Time", - "Category", - "Accesibility", - "Address", - "Features", - "Image", - "WebSite", - "GoogleMap", - ], - ...data.map((i) => [ - i.name, - i.rating, - i.reviewsCount, - i.phone, - i.time, - i.category, - i.isAccessible, - i.address, - i.features.join(" - "), - i.image, - i.website, - i.mapLink, - ]), - ] - .map((row) => row.join(",")) - .join("\n"); - data.forEach((i) => { - console.log(i); - }); + const header = Object.keys(data[0]); + const csv = [ + header.join(","), + // eslint-disable-next-line + ...data.map((row: any) => + header.map((fieldName) => { + const field = row[fieldName as keyof MapItem]; + return JSON.stringify( + Array.isArray(field) ? field.join(" - ") : field, + (_, value) => value ?? "", + ).replace(/\\"/g, '""'); + }), + ), + ].join("\n"); - const blob = new Blob([csvValues], { type: "text/csv" }); + const blob = new Blob([csv], { type: "text/csv" }); - const url = URL.createObjectURL(blob); - const link = document.createElement("a"); - link.href = url; - link.download = fileName; - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - URL.revokeObjectURL(url); + downloadFile(blob, fileName); }; export const downloadMapItemsJSON = @@ -55,12 +27,16 @@ export const downloadMapItemsJSON = const json = JSON.stringify(data, null, 2); const blob = new Blob([json], { type: "application/json" }); - const url = URL.createObjectURL(blob); - const link = document.createElement("a"); - link.href = url; - link.download = fileName; - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - URL.revokeObjectURL(url); + downloadFile(blob, fileName); }; + +const downloadFile = (file: Blob, fileName: string) => { + const url = URL.createObjectURL(file); + const link = document.createElement("a"); + link.href = url; + link.download = fileName; + document.body.appendChild(link); + link.click(); + document.body.removeChild(link); + URL.revokeObjectURL(url); +};