Convert an array of objects to CSV string in JavaScript
Tags: javascript, beginners, codenewbie
Published: 2020-10-29 19:27:29

On some occasions at work, we've needed to generate a CSV string on the server-side to send to our front-end app where the user can download a spreadsheet file e.g. report. 

Naturally, there are already packages out there that can handle a variety of CSV use cases, but we just wanted a simple solution in JavaScript as we knew that the data structure coming from our database was always going to be an array of objects.

Before we continue though, it's worth pointing out that we'll be using a few JavaScript methods and techniques in the solution that you may or may not already be familiar with:

* [Array.prototype.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
* [Array.prototype.join()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join)
* [Spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)

If any of the above seem a little alien to you right now, then feel free to take a quick pause here to check them out and come back when you're feeling more comfortable with them.

*****************************************************************

Welcome back if you took that break 👋

So, how do we get from an array of objects to a CSV string while ensuring that the correct data will be displayed in the column headers and rows?

Let's start by creating our array of objects:

```javascript
const itemsArray = [
      { itemId: 1, itemRef: "Item 001" },
      { itemId: 2, itemRef: "Item 002" },
      { itemId: 3, itemRef: "Item 003" }
    ];

``` 

The first step towards creating the CSV string is to define our column headers and extract the key-value pairs into their own arrays:

```javascript
const csvString = [
    [
      "Item ID",
      "Item Reference"
    ],
    ...itemsArray.map(item => [
      item.itemId,
      item.itemRef
    ])
  ];

console.log(csvString);
/*
   [
    ["Item ID", "Item Reference"],
    [1, "Item 001"],
    [2, "Item 002"],
    [3, "Item 003"]
   ]
*/
```

Now that we have all our data in arrays, we can use our `.map()` and `.join()` methods to bring everything together:

```javascript
const csvString = [
    [
      "Item ID",
      "Item Reference"
    ],
    ...itemsArray.map(item => [
      item.itemId,
      item.itemRef
    ])
  ]
   .map(e => e.join(",")) 
   .join("\n");

console.log(csvString);
/*
  "Item ID,Item Reference
  1,Item 001
  2,Item 002
  3,Item 003"
*/
```

What happens here then? Well, the first `map/join` combo combines the array of 4 arrays into a single array containing the headers and key-value pairs as string types e.g. "1,Item 001". Then, the final `join` is needed to convert the single array into a string.

*****************************************************************

In this post, we managed to convert an array of objects into a CSV string using some helpful array methods and the spread syntax in JavaScript. 

Please copy and experiment with the above code and feel free to ask me any questions on here or over on [Twitter]("https://twitter.com/samueldjones").

Thanks for reading!