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

JavascriptWeb DevelopmentFront End Technology

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?'
str.indexOf('a');

Output

4

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

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

Output

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

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 = arr.map( item => item/2) //Dividing every number by 2

Output

[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(' ');

Output

[‘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]
arr.reduce(function(accumulator,currentValue){
   return accumulator+currentValue;
},0)

Output

20

Approach

  • 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 ‘\n’ as the first occurrence.

  • The Data values are stored using “\n” 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>
<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('\n')).split(delimiter);
     
         /* Storing the value of each cell*/
         const titleValues = data.slice(data
            .indexOf('\n') + 1).split('\n');
     
         /* 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\nSteve,001,50000\nBill,002,60000";
      console.log(CSVstring_to_Array(inputString1));
      var inputString2 = "ProductName,Price,Category
      \nSmartphone,10000,Electronics\nFace
      Cream,500,Beauty\nShoes,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

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

raja
Updated on 22-Apr-2022 13:59:44

Advertisements