How to Convert CSV to an Array in JavaScript

You can the csvtojson library to quickly convert a CSV file or string to an array of objects in JavaScript:

index.js

import csvToJson from 'csvtojson';

const csvFilePath = 'data.csv';


const array = await csvToJson().fromFile(csvFilePath);

console.log(array);

For a data.csv file like this:

data.csv

color,maxSpeed,age
"red",120,2
"blue",100,3
"green",130,2

This will be the resulting array:

Output

[
  { color: 'red', maxSpeed: '120', age: '2' },
  { color: 'blue', maxSpeed: '100', age: '3' },
  { color: 'green', maxSpeed: '130', age: '2' }
]

Install csvtojson

Before using csvtojson, you’ll need to install it in our project. You can do this with the NPM or Yarn CLI.

npm i csvtojson

# Yarn
yarn add csvtojson

After installation, you’ll be able to import it into a JavaScript module, like this:

import csvToJson from 'csvtojson';

// CommonJS
const csvToJson = require('csvtojson');

Convert CSV file to array with fromFile()

We call the default export function of the csvtojson module to create the object that will convert the CSV to the array. This object has a bunch of methods, each related in some way to the conversion of CSV to a JavaScript object, and fromFile() is one of them.

It accepts the name of the CSV file to convert, and returns a Promise, as the conversion is an asynchronous process. The Promise will resolve with the resulting JSON string.

Convert CSV string to array with fromString()

To convert from a CSV data string directly, instead of a file, you can use the also asynchronous fromString() method of the converter object instead:

index.js

import csvToJson from 'csvtojson';

const csv = `"First Name","Last Name","Age"
"Russell","Castillo",23
"Christy","Harper",35
"Eleanor","Mark",26`;

const array = await csvToJson().fromString(csv);

console.log(array);

Output

[
  { 'First Name': 'Russell', 'Last Name': 'Castillo', Age: '23' },
  { 'First Name': 'Christy', 'Last Name': 'Harper', Age: '35' },
  { 'First Name': 'Eleanor', 'Last Name': 'Mark', Age: '26' }
]

Customize conversion of CSV to array

The default export function of csvtojson accepts an object used to specify options to customize the conversion process.

One such option is header, an array used to specify the headers in the CSV data.

index.js

import csvToJson from 'csvtojson';

const csv = `"First Name","Last Name","Age"
"Russell","Castillo",23
"Christy","Harper",35
"Eleanor","Mark",26`;

const array = await csvToJson({
  headers: ['firstName', 'lastName', 'age'],
}).fromString(csv);

console.log(array);

Output

[
  { firstName: 'Russell', lastName: 'Castillo', age: '23' },
  { firstName: 'Christy', lastName: 'Harper', age: '35' },
  { firstName: 'Eleanor', lastName: 'Mark', age: '26' }
]

Another is delimeter, used to indicate the character that separates the columns:

import csvToJson from 'csvtojson';

const csv = `"First Name"|"Last Name"|"Age"
"Russell"|"Castillo"|23
"Christy"|"Harper"|35
"Eleanor"|"Mark"|26`;

const array = await csvToJson({
  headers: ['firstName', 'lastName', 'age'],
  delimiter: '|',
}).fromString(csv);

Output

[
  { firstName: 'Russell', lastName: 'Castillo', age: '23' },
  { firstName: 'Christy', lastName: 'Harper', age: '35' },
  { firstName: 'Eleanor', lastName: 'Mark', age: '26' }
]

We also have ignoreColumns, an option that instructs the converter to ignore certain columns, using a regular expression.

import csvToJson from 'csvtojson';

const csv = `"First Name"|"Last Name"|"Age"
"Russell"|"Castillo"|23
"Christy"|"Harper"|35
"Eleanor"|"Mark"|26`;

const array = await csvToJson({
  headers: ['firstName', 'lastName', 'age'],
  delimiter: '|',
  ignoreColumns: /lastName/,
}).fromString(csv);

console.log(array);

Output

[
  { firstName: 'Russell', age: '23' },
  { firstName: 'Christy', age: '35' },
  { firstName: 'Eleanor', age: '26' }
]

Convert CSV to array of rows

By setting the output option to 'csv', we can produce a list of arrays, where each array represents a row, containing the value of all columns of that row.

For example:

index.js

import csvToJson from 'csvtojson';

const csv = `color,maxSpeed,age
"red",120,2
"blue",100,3
"green",130,2`;

const array = await csvToJson({
  output: 'csv',
}).fromString(csv);

console.log(array);

Output

[
  [ 'red', '120', '2' ],
  [ 'blue', '100', '3' ],
  [ 'green', '130', '2' ]
]

Native conversion of CSV to array

It’s also possible to convert CSV to a JavaScript array without using any third-party libraries.

index.js

function csvToArray(csv) {
  // \n or \r\n depending on the EOL sequence
  const lines = csv.split('\n');
  const delimeter = ',';

  const result = [];

  const headers = lines[0].split(delimeter);

  for (const line of lines) {
    const obj = {};
    const row = line.split(delimeter);

    for (let i = 0; i < headers.length; i++) {
      const header = headers[i];
      obj[header] = row[i];
    }

    result.push(obj);
  }

  // Prettify output
  return JSON.stringify(result, null, 2);
}

const csv = `color,maxSpeed,age
"red",120,2
"blue",100,3
"green",130,2`;

const array = csvToArray(csv);

console.log(array);

Output

[
  {
    "color": "color",
    "maxSpeed": "maxSpeed",
    "age": "age"
  },
  {
    "color": "\"red\"",
    "maxSpeed": "120",
    "age": "2"
  },
  {
    "color": "\"blue\"",
    "maxSpeed": "100",
    "age": "3"
  },
  {
    "color": "\"green\"",
    "maxSpeed": "130",
    "age": "2"
  }
]

You can modify the code above to allow for varying and more complex CSV data.



11 Amazing New JavaScript Features in ES13

This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.

11 Amazing New JavaScript Features in ES13

Sign up and receive a free copy immediately.

Leave a Comment

Your email address will not be published. Required fields are marked *