Export Array of Objects to CSV JavaScript

Export Array of Objects to CSV JavaScript
Code Snippet:javascript object to csv
Author: Jacqueline Walsh
Published: May 2, 2024
Last Updated: May 2, 2024
Downloads: 39
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code helps export an array of objects to a CSV file. It converts data into a downloadable CSV format. The function `downloadCSV` facilitates downloading CSV files from webpages.

You can use this code on your website to offer users a way to download data in CSV format. It simplifies data export, enhancing user experience. This code adds functionality for exporting data, improving website utility.

How to Export an Array of Objects to CSV in JavaScript

1. First, include a link or button element on your webpage that users can click to trigger the CSV download. In the example code, we use an anchor (<a>) tag with an onclick attribute to call the downloadCSV function.

<a href='#' 
        onclick='downloadCSV({ filename: "stock-data.csv" });'
    >Download CSV</a>

2. Next, define your data as an array of objects in JavaScript. Each object represents a row of data, with keys and corresponding values. In our example, we have stockData, which contains information about stocks such as symbol, company name, and price.

To convert your array of objects to a CSV format, use the convertArrayOfObjectsToCSV function. This function takes an object with the data array as a parameter and returns a CSV string. It iterates through each object, extracts its keys as column headers, and appends the values as rows.

Finally, use the downloadCSV function to initiate the download of the CSV file. This function creates a temporary link with the CSV data encoded as a data URL. When the link is clicked, the browser prompts the user to save the file with the specified filename.

var stockData = [  
        {
            Symbol: "AAPL",
            Company: "Apple Inc.",
            Price: 132.54
        },
        {
            Symbol: "INTC",
            Company: "Intel Corporation",
            Price: 33.45
        },
        {
            Symbol: "GOOG",
            Company: "Google Inc",
            Price: 554.52
        },
    ];
function convertArrayOfObjectsToCSV(args) {  
        var result, ctr, keys, columnDelimiter, lineDelimiter, data;

        data = args.data || null;
        if (data == null || !data.length) {
            return null;
        }

        columnDelimiter = args.columnDelimiter || ',';
        lineDelimiter = args.lineDelimiter || '\n';

        keys = Object.keys(data[0]);

        result = '';
        result += keys.join(columnDelimiter);
        result += lineDelimiter;

        data.forEach(function(item) {
            ctr = 0;
            keys.forEach(function(key) {
                if (ctr > 0) result += columnDelimiter;

                result += item[key];
                ctr++;
            });
            result += lineDelimiter;
        });

        return result;
    }
function downloadCSV(args) {  
        var data, filename, link;
        var csv = convertArrayOfObjectsToCSV({
            data: stockData
        });
        if (csv == null) return;

        filename = args.filename || 'export.csv';

        if (!csv.match(/^data:text\/csv/i)) {
           csv = 'data:text/csv;charset=utf-8,' + csv;
         }
        data = encodeURI(csv);

        link = document.createElement('a');
        link.setAttribute('href', data);
        link.setAttribute('download', filename);
        link.click();
    }

That’s all! hopefully, you have successfully created functionality to export an array of objects to CSV using JavaScript. If you have any questions or suggestions, feel free to comment below.

Leave a Comment