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
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read