The Wayback Machine - https://web.archive.org/web/20240627235229/https://www.geeksforgeeks.org/how-to-convert-csv-string-file-to-a-2d-array-of-objects-using-javascript/
Open In App

How to convert CSV string file to a 2D array of objects using JavaScript ?

Last Updated : 03 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

A CSV is a comma-separated values file with a .csv extension, which allows data to be saved in a tabular format. 

In this article, we will learn to convert the data of a CSV string to a 2D array of objects, where the first row of the string is the title row using JavaScript.

Given a comma-separated values (CSV) string to a 2D array, using Javascript function.

Input: 'Name,Roll Number\nRohan,01\nAryan,02' 

Output:  [
             {Name: "Rohan", Roll Number: "01"},
             {Name: "Aryan", Roll Number: "02"}
        ]
// With delimiter ;    
    
Input: 'Name;Roll Number\nRohan;01\nAryan;02' 
        
Output:    [
             {Name: "Rohan", Roll Number: "01"},
             {Name: "Aryan", Roll Number: "02"}
        ]    

We must know some array and string prototype functions that will be helpful in this regard.

indexOf function: The String.prototype.indexOf() function finds the index of the first occurrence of the argument string in the given string and the value returned is in the 0-based index.

Example:

str = 'How\nare\nyou?' 

str.indexOf('\n');

Output:

3

Slice function: The Array.prototype.slice() method returns a new array containing a portion of the array on which it is implemented and the original array remains the same.

Example: 

['a','b','c','d'].slice(1)

Output:

 ['b','c','d']

Map function: The Array.prototype.map() method returns a new array with the results of calling a provided function on every element.

Example:

arr = [2, 4, 8, 16]

// Dividing each element of the array by 2
newArr = arr.map( item => item/2) 

Output:

[1, 2, 4, 8]

Split function: The String.prototype.split() method is used to split the given string into an array of strings by separating it into substrings using a specified separator provided in the argument.

Example:

str = "Geeks for Geeks"

// Split the array when ' ' is located
arr = str.split(' ');

Output:

[ 'Geeks', 'for', 'Geeks' ]

Reduce function: The Array.prototype.reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each element of the array from left to right and the return value of the function is stored in an accumulator.

Example:

 arr = [2,4,6,8]
 
 // Here 0 is the initial value of the accumulator
 // while traversing, currentValue has been added
 
 arr.reduce(function(accumulator,currentValue){
     return accumulator+currentValue;
 },0)

Output:

20

Approach:

  • The JavaScript string slice() method extracts parts of a string and returns the extracted parts in a new string taking ‘\n’ as the first occurrence.
  • Data Values are stored using “\n” as the delimiter.
  • JavaScript map() function will iterate over all values of the title values array and append each object at the end of the array
  • The “storeKeyValue” variable is used to store each key with its respective values.

Example: In this example, we will convert a comma-separated value (CSV) to a javascript array using the slice(), map(), split(), and reduce() methods of Javascript.

Javascript




<script>
    function CSVstring_to_Array(data, delimiter = ',') {
     
        /* This variable will collect all the titles
           from the data variable
           ["Name", "Roll Number"] */
         
        const titles = data.slice(0, data
            .indexOf('\n')).split(delimiter);
     
        /* This variable will store the values
           from the data
           [ 'Rohan,01', 'Aryan,02' ] */
        const titleValues = data.slice(data
            .indexOf('\n') + 1).split('\n');
     
        /* Map function will iterate over all
           values of title values array and
           append each object at the end of
           the array */
        const ansArray = titleValues.map(function (v) {
     
            /* Values variable will store individual
               title values        
               [ 'Rohan', '01' ] */
            const values = v.split(delimiter);
     
            /* storeKeyValue variable will store
               object containing each title
               with their respective values i.e
               { Name: 'Rohan', 'Roll Number': '01' } */
            const storeKeyValue = titles.reduce(
                function (obj, title, index) {
                    obj[title] = values[index];
                    return obj;
                }, {});
     
            return storeKeyValue;
        });
     
        return ansArray;
    };
     
    var inputString1 = "Name,Roll Number\nRohan,01\nAryan,02";
    console.log(CSVstring_to_Array(inputString1));
     
    var inputString2 = "Name;Roll Number\nRohan;01\nAryan;02";
    console.log(CSVstring_to_Array(inputString2,';'));
</script>


Output:



Similar Reads

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 val
3 min read
How to Convert Array of Objects into Unique Array of Objects in JavaScript ?
Arrays of objects are a common data structure in JavaScript, often used to store and manipulate collections of related data. However, there are scenarios where you may need to convert an array of objects into a unique array, removing any duplicate objects based on specific criteria. JavaScript has various methods to convert an array of objects into
6 min read
Convert JSON file into CSV file and displaying the data using Node.js
There are so many ways to store data for better understanding for individual purposes, in few cases, JSON files will be more suitable in few cases, CSV files, and there are also lots of other types as well like XML, etc. In this article, we will convert the JSON file data into CSV file data and also display that through Node.js. JSON stands for Jav
3 min read
CSV File Format | .csv Extension
What are CSV Files?The full form of CSV is Comma-separated values. Comma-separated value is a simple yet powerful file format to store and exchange data. Values are separated using commas in this plain text file format. CSV files are often used to store data in a tabular format, such as spreadsheets or databases. These files are easy to create and
3 min read
Filter Array of Objects with Another Array of Objects in JavaScript
Filtering an array of objects with another array in JavaScript involves comparing and including objects based on specific criteria. Below are the approaches to filter an array of objects with another array of objects in JavaScript: Table of Content Using filter and includes MethodsUsing LoopingUsing reduce MethodUsing filter and includes MethodsIn
3 min read
How to Convert CSV to JSON file and vice-versa in JavaScript ?
CSV files are a common file format used to store data in a table-like manner. They can be particularly useful when a user intends to download structured information in a way that they can easily open and read on their local machine. CSV files are ideal for this because of their portability and universality. In this article, we will explain how to c
3 min read
How to Update an Array of Objects with Another Array of Objects using Lodash?
Updating an array of objects with another array of objects involves merging or updating objects in the first array with corresponding objects from the second array. Below are the approaches to update an array of objects with another array of objects in the Lodash library: Table of Content Using _.merge function from lodashUsing _.mergeWith function
2 min read
How to convert an array to CSV file in PHP ?
To convert an array into a CSV file we can use fputcsv() function. The fputcsv() function is used to format a line as CSV (comma separated values) file and writes it to an open file. The file which has to be read and the fields are sent as parameters to the fputcsv() function and it returns the length of the written string on success or FALSE on fa
2 min read
How to convert a 2D array to a comma-separated values (CSV) string in JavaScript ?
Given a 2D array, we have to convert it to a comma-separated values (CSV) string using JS. Input:[ [ "a" , "b"] , [ "c" ,"d" ] ]Output:"a,b c,d"Input:[ [ "1", "2"]["3", "4"]["5", "6"] ]Output:"1,23,45,6"To achieve this, we must know some array prototype functions which will be helpful in this regard: Join function: The Array.prototype.join( ) funct
4 min read
How to Separate Array of Objects into Multiple Objects in JavaScript ?
In JavaScript, the task of separating an array of objects into multiple objects involves organizing and restructuring data based on specific criteria or properties. This process is often necessary when dealing with datasets that need to be grouped or segmented for easier analysis or manipulation. There are various methods to achieve this separation
4 min read
three90RightbarBannerImg