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 values (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.
JavaScript: Tips of the Day
Chunks an array into n smaller arrays
Example:
const tips_chunkIntoN = (arr, n) => { const size = Math.ceil(arr.length / n); return Array.from({ length: n }, (v, i) => arr.slice(i * size, i * size + size) ); } console.log(tips_chunkIntoN([1, 2, 3, 4, 5, 6, 7,8], 4));
Output:
[[1,2],[3,4],[5,6],[7,8]]
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework