How to convert CSV string file to a 2D array of objects using JavaScript ?
Last Updated :
03 Jan, 2023
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
How to Convert String to Array of Objects JavaScript ? Given a string, the task is to convert the given string to an array of objects using JavaScript. It is a common task, especially when working with JSON data received from a server or API. Below are the methods that allow us to convert string to an array of objects:Table of ContentUsing JSON.parse()
4 min read
How to Convert String of Objects to Array in JavaScript ? This article will show you how to convert a string of objects to an array in JavaScript. You have a string representing objects, and you need to convert it into an actual array of objects for further processing. This is a common scenario when dealing with JSON data received from a server or stored i
3 min read
How to convert an object to string using JavaScript ? To convert an object to string using JavaScript we can use the available methods like string constructor, concatenation operator etc. Let's first create a JavaScript object. JavaScript // Input object let obj_to_str = { name: "GeeksForGeeks", city: "Noida", contact: 2488 }; Examp
4 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
4 min read
How to convert a map to array of objects in JavaScript? A map in JavaScript is a set of unique key and value pairs that can hold multiple values with only a single occurrence. Sometimes, you may be required to convert a map into an array of objects that contains the key-value pairs of the map as the values of the object keys. Let us discuss some methods
6 min read