JavaScript : Convert a comma-separated values string to a 2D array of objects
JavaScript fundamental (ES6 Syntax): Exercise-4 with Solution
Write a JavaScript program to convert a comma-separated value (CSV) string to a 2D array of objects. The first row of the string is used as the title row.
- Use Array.prototype.slice() and Array.prototype.indexOf('\n') and String.prototype.split(delimiter) to separate the first row (title row) into values.
- Use String.prototype.split('\n') to create a string for each row, then Array.prototype.map() and String.prototype.split(delimiter) to separate the values in each row.
- Use Array.prototype.reduce() to create an object for each row's values, with the keys parsed from the title row.
- Omit the second argument, delimiter, to use a default delimiter of ,.
Sample Solution:
JavaScript Code:
//#Source https://bit.ly/2neWfJ2
const CSV_to_JSON = (data, delimiter = ',') => {
const titles = data.slice(0, data.indexOf('\n')).split(delimiter);
return data
.slice(data.indexOf('\n') + 1)
.split('\n')
.map(v => {
const values = v.split(delimiter);
return titles.reduce((obj, title, index) => ((obj[title] = values[index]), obj), {});
});
};
console.log(CSV_to_JSON('col1,col2\na,b\nc,d')); // [{'col1': 'a', 'col2': 'b'}, {'col1': 'c', 'col2': 'd'}];
console.log(CSV_to_JSON('col1;col2\na;b\nc;d', ';')); // [{'col1': 'a', 'col2': 'b'}, {'col1': 'c', 'col2': 'd'}];
Sample Output:
[{"col1":"a","col2":"b"},{"col1":"c","col2":"d"}] [{"col1":"a","col2":"b"},{"col1":"c","col2":"d"}]
Flowchart:

Live Demo:
See the Pen javascript-basic-exercise-1-4 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Write a JavaScript program to converts a comma-separated values (CSV) string to a 2D array.
Next: Write a JavaScript program to convert an array of objects to a comma-separated values (CSV) string that contains only the columns specified.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join