JavaScript: Converting a CSV string file to a 2D array of objects

A CSV is a comma-separated value that is stored in a file with the .csv extension. This allows the user to store data in a tabular or spreadsheet format.

In this article, we will be exploring how to convert the data of a CSV string to 2D array objects where the first row of the string defines the file headers. We will be first reading this row and then mapping the remaining values with them.

We will be using the following function that will act as a prototype function from array and string since it will be helpful in mapping the data once the file is read −

indexOf Function

The String.prototype.indexOf() functions returns the first index of the first occurrence of this argument string. The value returned is in the 0-based index and -1 is returned if there is no such occurrence of this type.

For Example

str = 'How are you?'



Slice Function

This method returns a new array containing a portion of the array where it is implemented and the original array will remain the same.

For Example




Map Function

This method returns a new array after mapping the values with the results of calling a provided function on every element.

For Example

arr = [2, 4, 8, 16]
newArr = item => item/2) //Dividing every number by 2


[1, 2, 4, 8]

Split Function

This method is used for splitting up the given string into an array of strings. The string is separated into multiple substrings by using a specified separator provided in the argument.

For Example

str = 'Tutorials Point'
arr = str.split(' ');


[‘Tutorials’, ‘Point’]

Reduce Function

This method in JavaScript is used for reducing the array to a single value that executes a provided function for each element of the array from left to right and returns the value of the function. This value is stored in an accumulator.

For Example

arr = [2,4,6,8]
   return accumulator+currentValue;




  • We will be using the JavaScript slice() method for extracting the parts of the string and returning the extracted parts to a new string taking ‘
    ’ as the first occurrence.

  • The Data values are stored using “
    ” as the delimiter.

  • We will iterate over all the values and then map each value at the end of the array.

  • The “storeKeyValue” variable will be used to store each key with its respective values.

Example 1

In the below example, we are mapping the value from a CSV string to a 2D array of objects.

# index.html

<!DOCTYPE html>
   <h1 style="color: green;">
      Welcome To Tutorials Point
      function CSVstring_to_Array(data, delimiter = ',') {
         /* Collecting the titles */
         const titles = data.slice(0, data
')).split(delimiter);                /* Storing the value of each cell*/          const titleValues = data.slice(data             .indexOf('
') + 1).split('
');                /* Mapping these values with the title */          const ansArray = (v) {              /* Values variable will store individual             title values*/             const values = v.split(delimiter);                       /* storeKeyValue variable will store             object containing each title             with their respective values*/             const storeKeyValue = titles.reduce(                function (obj, title, index) {                   obj[title] = values[index];                   return obj;                }, {});             return storeKeyValue;          });          return ansArray;       };       var inputString1 = "Name,EmpId, Salary
Bill,002,60000";       console.log(CSVstring_to_Array(inputString1));       var inputString2 = "ProductName,Price,Category      
Face       Cream,500,Beauty
Shoes,2000,Footwear";       console.log(CSVstring_to_Array(inputString2,';'));    </script> </body> </html>


On successful execution of the above program, the browser will display the following result −

Welcome To Tutorials Point

And in the console, you will find all the computed results, see the screenshot below −

Updated on: 22-Apr-2022


Kickstart Your Career

Get certified by completing the course

Get Started