Open In App

Write a program to convert an array of objects to a CSV string that contains only the columns specified using JavaScript

When we want to store multiple values in one variable then instead of a variable, we use an array. which allows you to store multiple types of data for example you could have a string, an integer, etc.

In this article, we will learn to convert the array objects to CSV string data. 



Given array objects ( key: value ) to CSV string comma-separated values and keys as header.

Input :  [
             Name: "geek", 
             Roll Number:  121,
             Age: 56
         ] 
           
Output:  Name, Roll Number, Age
         geek, 121, 56

Before getting into code we must know some about the following Array functions.



Approach:

Example: Below is the implementation of the above approach:




<script>
    const objectToCsv = function (data) {
     
        const csvRows = [];
     
        /* Get headers as every csv data format
        has header (head means column name)
        so objects key is nothing but column name
        for csv data using Object.key() function.
        We fetch key of object as column name for
        csv */
        const headers = Object.keys(data[0]);
     
        /* Using push() method we push fetched
           data into csvRows[] array */
        csvRows.push(headers.join(','));
     
        // Loop to get value of each objects key
        for (const row of data) {
            const values = headers.map(header => {
                const val = row[header]
                return `"${val}"`;
            });
     
            // To add, separator between each value
            csvRows.push(values.join(','));
        }
     
        /* To add new line for each objects values
           and this return statement array csvRows
           to this function.*/
        return csvRows.join('\n');
    };
     
    const data = [{
        "firstname": "geeks",
        "lastname": "org",
        "age": 12
    },
    {
        "firstname": "devendra",
        "lastname": "salunke",
        "age": 31
    },
    {
        "firstname": "virat",
        "lastname": "kohli",
        "age": 34
    },
    ];
     
    // Data passed as parameter
    const csvData = objectToCsv(data);
    console.log(csvData);
</script>

Output: 

firstname,lastname,age
"geeks","org","12"
"devendra","salunke","31"
"virat","kohli","34"

Article Tags :