DEV Community

sanderdebr
sanderdebr

Posted on

Converting CSV string to a 2D array of objects in ES6

Converting CSV string to a 2D array of objects in ES6

In this article I will explain how to convert a comma-separated values (CSV) string to a 2D array of object using Javascript.

Let’s say you have a CSV list of users ordered in three columns: id, name and email and you want to convert it to JSON to send it over an API for example.

First we’ll set up a function that takes in two parameters: a string and the delimiter by which we need to divide the rows by. Then we grab the title by slicing the first row and splitting it by our delimiter. If our delimiter is not set, we’ll set it to a comma by default.

Now we have the titles in an array, let’s get the rows inside an array. We do this by mapping over our rows array and splitting each row by our delimiter.

Now comes the exciting part. Inside our map loop we will convert the current row to an object by running the reduce() function on our titles array. This way we can set the correct value for each title. Then we’ll return our created object back and repeat the process for every row.

Great! Let’s refractor our code and make it shorter. Also we can test it with a different delimiter.

That’s it! Hope you’ve learned something from this short article.

Top comments (0)