Convert CSV String to 2D Array of Objects in JavaScript



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 learn to convert the data of a CSV string to 2D array objects in JavaScript, 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 help map the data once the file is read ?

indexOf Function

The String.indexOf() functions return 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.

Example

str = 'How are you?'
str.indexOf('a');

Output

4

Slice Function

The slice() method returns a new array containing a portion of the array where it is implemented and the original array will remain the same.

Example

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

Output

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

Map Function

The map() method returns a new array after mapping the values with the results of calling a provided function on every element.

Example

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

Output

[1, 2, 4, 8]

Split Function

The split() 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.

Example

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

Output

[?Tutorials', ?Point']

Reduce Function

The reduce() 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.

Example

arr = [2,4,6,8]
arr.reduce(function(accumulator,currentValue){
   return accumulator+currentValue;
},0)

Output

20

Following are the steps to convert a CSV string file to a 2D array of objects ?

  • 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 

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

# index.html

<!DOCTYPE html>
<html>
<head>
   <title></title>
</head>
<body>
   <h1 style="color: green;">
      Welcome To Tutorials Point
   </h1>
   <script>
      function CSVstring_to_Array(data, delimiter = ',') {
         /* Collecting the titles */
         const titles = data.slice(0, data
            .indexOf('
')).split(delimiter); /* Storing the value of each cell*/ const titleValues = data.slice(data .indexOf('
') + 1).split('
'); /* Mapping these values with the title */ const ansArray = titleValues.map(function (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
Steve,001,50000
Bill,002,60000"; console.log(CSVstring_to_Array(inputString1)); var inputString2 = "ProductName,Price,Category
Smartphone,10000,Electronics
Face Cream,500,Beauty
Shoes,2000,Footwear"; console.log(CSVstring_to_Array(inputString2,';')); </script> </body> </html>

Output

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

Welcome To Tutorials Point

In the console, you will find all the computed results, see the screenshot below ?

Updated on: 2024-12-26T20:46:20+05:30

702 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements