How do you export a JavaScript array of objects to a downloadable CSV file on the client side? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you export a JavaScript array of objects to a downloadable CSV file on the client side?

message-square
0

To export a JavaScript array of objects to a downloadable CSV file on the client side, validate that the input is a non-empty Array of plain/record objects (Array.isArray(rows)), serialize headers and cells safely inside a try / catch block—escaping double quotes (" -> ""), wrapping fields containing delimiters, quotes, or newlines in "...", neutralizing formula-injection prefixes (=, +, -, @, \t, \r) when appropriate, and storing column metadata/mappings in a Map—then create a Blob (new Blob([csvString], { type: "text/csv;charset=utf-8;" })), generate a temporary object URL via URL.createObjectURL(blob), trigger a download with an anchor element (download="export.csv"), and revoke the object URL via URL.revokeObjectURL(url).


1. Converting an Array of Objects into Escaped CSV String and Map-Backed Columns

Validate rows (Array.isArray), collect column keys in a Map so dynamic column names never collide with Object.prototype properties, and escape every cell properly inside try / catch:

// Convert an Array of objects into a properly escaped CSV string using a Map for column order
function convertObjectsArrayToCsv(rows, {
  delimiter = ",",
  includeBom = true,
  escapeFormulaPrefixes = true
} = {}) {
  if (!Array.isArray(rows)) {
    throw new TypeError("Expected rows to be an Array instance.");
  }
  if (typeof delimiter !== "string" || delimiter.length !== 1) {
    throw new TypeError("Expected delimiter to be a single-character string.");
  }
  if (typeof includeBom !== "boolean") {
    throw new TypeError("Expected includeBom to be a boolean.");
  }
  if (typeof escapeFormulaPrefixes !== "boolean") {
    throw new TypeError("Expected escapeFormulaPrefixes to be a boolean.");
  }

  try {
    const columnsMap = new Map();

    for (const row of rows) {
      if (typeof row !== "object" || row === null || Array.isArray(row)) {
        throw new TypeError("Expected every element in rows to be a non-null plain/record object.");
      }
      for (const key of Object.keys(row)) {
        if (!columnsMap.has(key)) {
          columnsMap.set(key, columnsMap.size);
        }
      }
    }

    if (columnsMap.size === 0) {
      return includeBom ? "\uFEFF" : "";
    }

    const formatCell = (rawValue) => {
      let textValue = "";
      if (rawValue === null || rawValue === undefined) {
        textValue = "";
      } else if (rawValue instanceof Date) {
        textValue = Number.isNaN(rawValue.getTime()) ? "" : rawValue.toISOString();
      } else if (typeof rawValue === "object") {
        textValue = JSON.stringify(rawValue);
      } else {
        textValue = String(rawValue);
      }

      if (escapeFormulaPrefixes && /^[=+\-@\t\r]/.test(textValue)) {
        textValue = `'${textValue}`;
      }

      const needsQuotes =
        textValue.includes('"') ||
        textValue.includes(delimiter) ||
        textValue.includes("\n") ||
        textValue.includes("\r");

      if (!needsQuotes) {
        return textValue;
      }

      const escapedInner = textValue.replace(/"/g, '""');
      return `"${escapedInner}"`; };  const orderedHeaders = Array.from(columnsMap.keys()); const headerLine = orderedHeaders.map((colName) => formatCell(colName)).join(delimiter);  const dataLines = rows.map((row) => { return orderedHeaders .map((colKey) => { const hasOwn = Object.prototype.hasOwnProperty.call(row, colKey); return formatCell(hasOwn ? row[colKey] : ""); }) .join(delimiter); });  const csvBody = [headerLine, ...dataLines].join("\r\n"); return includeBom ? `\uFEFF${csvBody}` : csvBody;
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    throw new Error(`Failed converting objects array to CSV: ${message}`);
  }
}

// Example usage:
// try {
//   const records = [
//     { id: 1, name: "Ali, Khan", note: 'Quoted "value"\nLine 2' },
//     { id: 2, name: "Sara Ahmed", note: "=SUM(A1:A2)" }
//   ];
//   const csvOutput = convertObjectsArrayToCsv(records);
//   console.log("Generated CSV length:", csvOutput.length);
// } catch (error) {
//   console.error(`${error.name}:${error.message}`);
// }
  • Double internal quotes (") and wrap special fields: Prevents commas, line breaks, or quotes inside a field from breaking CSV columns or rows.
  • Use Map for column discovery: Avoids Object.prototype collisions (constructor, toString, hasOwnProperty) when object property names are dynamic.

2. Triggering a Browser File Download with Blob and URL.createObjectURL()

In the browser, validate document instanceof Document, typeof URL === "function", and a non-empty fileName, build a Blob, click a temporary <a> element with download, and clean up the object URL in try / catch:

// Trigger a client-side CSV file download from an Array of objects in the browser
function downloadObjectsAsCsv(rows, fileName = "export.csv", options = {}) {
  if (typeof document === "undefined" || !(document instanceof Document)) {
    throw new Error("Browser Document environment is required to trigger a CSV download.");
  }
  if (typeof URL === "undefined" || typeof URL.createObjectURL !== "function" || typeof URL.revokeObjectURL !== "function") {
    throw new Error("Browser URL object URL APIs are required to download a Blob.");
  }
  if (typeof fileName !== "string" || fileName.trim().length === 0) {
    throw new TypeError("Expected fileName to be a non-empty string.");
  }

  try {
    const csvContent = convertObjectsArrayToCsv(rows, options);
    const csvBlob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
    const objectUrl = URL.createObjectURL(csvBlob);

    const cleanName = fileName.trim().toLowerCase().endsWith(".csv")
      ? fileName.trim()
      : `${fileName.trim()}.csv`;

    const anchorEl = document.createElement("a");
    if (!(anchorEl instanceof HTMLAnchorElement)) {
      throw new Error("Failed creating HTMLAnchorElement for download.");
    }

    anchorEl.href = objectUrl;
    anchorEl.setAttribute("download", cleanName);
    anchorEl.style.display = "none";

    document.body.appendChild(anchorEl);
    anchorEl.click();
    document.body.removeChild(anchorEl);

    setTimeout(() => {
      try {
        URL.revokeObjectURL(objectUrl);
      } catch (revokeError) {
        const msg = revokeError instanceof Error ? revokeError.message : String(revokeError);
        console.error(`Failed revoking CSV object URL: ${msg}`);
      }
    }, 1000);

    return new Map([
      ["fileName", cleanName],
      ["rowCount", rows.length],
      ["byteSize", csvBlob.size]
    ]);
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    throw new Error(`Failed downloading CSV file "${fileName}": ${message}`);
  }
}

// Example usage (in browser):
// try {
//   const exportMeta = downloadObjectsAsCsv(
//     [{ orderId: "ORD-10", total: 2500 }, { orderId: "ORD-11", total: 4200 }],
//     "orders-report.csv"
//   );
//   console.log("Exported:", exportMeta.get("fileName"), exportMeta.get("byteSize"));
// } catch (error) {
//   console.error(`${error.name}:${error.message}`);
// }
  • Include UTF-8 BOM (\uFEFF) by default: Helps spreadsheet tools like Microsoft Excel open accented/non-ASCII characters cleanly as UTF-8.
  • Revoke objectUrl after triggering .click(): Prevents memory leaks from unrevoked Blob URLs over repeated exports.

3. Spreadsheet Formula Injection, Missing Keys, and Size Caveats

Keep these client-side CSV export details in mind in production apps:

  • Watch spreadsheet formula prefixes (=, +, -, @): Untrusted values starting with formula characters can execute formulas when opened in spreadsheet software unless prefixed or sanitized.
  • Sparse/heterogeneous objects across rows: Not every object in an array has identical keys—collecting all keys across rows ensures every row aligns to the full header set.
  • Large datasets (tens/hundreds of thousands of rows): Generating huge strings and Blobs in the main browser thread can cause UI lag—consider Web Workers, streaming, or server-side CSV generation for heavy exports.