tutorial

How to Capitalize the First Letter of Each Word in a String in JavaScript

To capitalize the first letter of each word in a string in JavaScript:

  1. Split the string into an array of words with .split('').
  2. Iterate over the words array with .map().
  3. For each word, return a new word that is an uppercase form of the word’s first letter added to the rest of the word.
  4. Join the words array into a string with .join(' ').

For example:

index.js

function capitalizeWords(str) {
  return str
    .toLowerCase()
    .split(' ')
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ');
}


// Welcome To Coding Beauty
console.log(capitalizeWords('WELCOME to coding beauty'));

// JavaScript And TypeScript
console.log(capitalizeWords('JAVASCRIPT AND TYPESCRIPT'));

Our capitalizeWords() function takes a string and returns a new string with all the words capitalized.

First, we use the toLowerCase() method to lowercase the entire string, ensuring that only the first letter of each word is uppercase.

// welcome to coding beauty
console.log('WELCOME to coding beauty'.toLowerCase());

Tip: If it’s not necessary for the remaining letters in each word to be lowercase, you can remove the call to the toLowerCase() method.

Then we call the String split() method on the string to split all the words into an array.

// [ 'welcome', 'to', 'coding', 'beauty' ]
console.log('welcome to coding beauty'.split(' '));

After creating the array, we call the map() method on it, with a callback function as an argument. This function will be called and return a result for each word in the array.

In the function, we get the word’s first character with charAt(), convert it to uppercase with toUpperCase(), and concatenate it with the rest of the string.

We use the String slice() method to get the remaining part of the string. Passing 1 to slice() makes it return the portion of the string from the second (index of 1) character to the end.

// [ 'Welcome', 'To', 'Coding', 'Beauty' ]
console.log(
  'welcome to coding beauty'
    .split(' ')
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
);

So map() returns an array containing all the words in the string, with each word’s first letter capitalized.

Lastly, we concatenate all the words in a single string, with the Array join() method.

Passing a space (' ') to join() separates the words by a space in the resulting string.

// Welcome To Coding Beauty
console.log(['Welcome', 'To', 'Coding', 'Beauty'].join(' '));

How to fix the “__dirname is not defined in ES module scope” error in JavaScript

The “__dirname is not defined in ES module scope” error happens in JavaScript when we try to access the __dirname global variable in an ES module. The __dirname and __filename global variables are defined in CommonJS modules, but not in ES modules.

The "__dirname is not defined in ES module scope" error occurring in JavaScript.
The “__dirname is not defined in ES module scope” error occurring in JavaScript.

We can fix the “__dirname is not defined in ES module scope” error by using certain functions to create a custom __dirname variable that works just like the global variable, containing the full path of the file’s current working directly.

index.js

import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);

const __dirname = path.dirname(__filename);

// C:/cb/cb-js
console.log(__dirname);

// C:\cb\cb-js\index.html
console.log(path.join(__dirname, 'index.html'));

The import.meta object contains context-specific metadata associated with a certain module, e.g., a module’s file URL.

// file:///C:/cb/cb-js/index.js
console.log(import.meta.url);

So we get the current module’s file URL and pass it to the fileURLToPath function from the url module, to convert it to a file path. fileURLToPath returns a fully-resolved, platform-specific Node.js file path.

// C:\cb\cb-js\index.js
console.log(fileURLToPath('file:///C:/cb/cb-js/index.js'));

After getting the file path, we pass it to the dirname method from the path module, to get the full directory path from the file path.

// C:\cb\cb-js
console.log(path.dirname('C:\\cb\\cb-js\\index.js'));

With this, we now have our own __dirname and __filename variables.

Here’s the output from logging them from a file on my computer.

Logging the "__dirname" and "__filename" variables to the console.
Logging the __dirname and __filename variables to the console.

__filename contains the absolute path of the current module file.

__dirname contains the absolute path of the current module file’s directory.

Create utility for __dirname and __filename

If we access the __dirname and __filename variables frequently, we can abstract the logic for creating them in a utility module and avoid unnecessary repetition.

file-dir-name.js

import { fileURLToPath } from 'url';
import { dirname } from 'path';

export default function fileDirName(meta) {
  const __filename = fileURLToPath(meta.url);

  const __dirname = dirname(__filename);

  return { __dirname, __filename };
}

We’ll be able to use this utility across the various other module files in our project.

index.js

import fileDirName from './file-dir-name.js';

const { __dirname, __filename } = fileDirName(import.meta);

// C:\cb\cb-js
console.log(__dirname);

// C:\cb\cb-js\index.js
console.log(__filename);

How to Use an Image as a Link in React

Related: How to Link an Image in React

To use an image as a link in React, wrap the image in an anchor (a) tag. Clicking an image link will make the browser navigate to the specified URL.

For example:

App.js

import cbLogo from './cb-logo.png';

export default function App() {
  return (
    <div>
      Click the logo to navigate to the site
      <br />
      <br />
      <a href="https://codingbeautydev.com" target="_blank" rel="noreferrer">
        <img src={cbLogo} alt="Coding Beauty logo"></img>
      </a>
    </div>
  );
}
The browser navigates to the URL when the image link is clicked.
The browser navigates to the URL when the image link is clicked.

We use an import statement to link the image into the file, and assign it to the src prop of the img element to display it.

The properties set on an a element will work as usual when it wraps an image. For instance, in the example, we set the a element’s target property to _blank, to open the URL in a new tab. Removing this will make it open in the same tab as normal.

We also set the rel prop to noreferrer for security purposes. It prevents the opened page from gaining access to any information about the page from which it was opened from.

For React Router, you can use an image as link by wrapping the image in a Link element.

For example:

ImagePages.jsx

import { Link } from 'react-router-dom';

export default function ImagesPage() {
  return (
    <div>
      <Link to="/nature" target="_blank" rel="noreferrer">
        <img src="/photos/tree-1.png" alt="Nature"></img>
      </Link>
    </div>
  );
}

How to Get an Input Field’s Value in React

To get the value of an input field in React:

  1. Create a state variable to store the input field’s value.
  2. Set an onChange event handler on the input field.
  3. In the event handler, assign event.target.value to the state variable.
  4. The state variable will contains the input field’s value at any given time.

For example:

App.js

import { useState } from 'react';

export default function App() {
  const [message, setMessage] = useState('');

  const [updated, setUpdated] = useState(message);

  const handleChange = (event) => {
    setMessage(event.target.value);
  };

  const handleClick = () => {
    //  "message" stores input field value
    setUpdated(message);
  };

  return (
    <div>
      <input
        type="text"
        id="message"
        name="message"
        onChange={handleChange}
        value={message}
      />

      <h2>Message: {message}</h2>

      <h2>Updated: {updated}</h2>

      <button onClick={handleClick}>Update</button>
    </div>
  );
}

With the useState hook, we create a state variable (message) to store the input field’s current value. We also create another state variable (updated) that will be updated with the input field value when the button is clicked.

We set an onChange event handler on the input field to execute an action. In the handler, we use the Event object’s target property to access the object representing the input element. The value property of this object contains the input value, so we pass it to setMessage to update message, and this reflects on the page.

After setting up the controlled input, we can now use message outside the handleChange handler to get the current value of the input field.

So in the onClick event handler we set on the button, we use setUpdated(message) to update the updated variable with the input field’s current value.

Get input value with ref

Alternatively, we can use a ref to get the value of an input field in React. After setting the ref on the input, we’ll be able to use the ref object to access the input field’s current value in the event handler.

App.js

import { useRef, useState } from 'react';

export default function App() {
  const inputRef = useRef(null);

  const [updated, setUpdated] = useState('');

  const handleKeyDown = (event) => {
    if (event.key === 'Enter') {
      setUpdated(inputRef.current.value);
    }
  };

  return (
    <div>
      <input
        ref={inputRef}
        type="text"
        id="message"
        name="message"
        onKeyDown={handleKeyDown}
      />

      <h2>Updated: {updated}</h2>
    </div>
  );
}

We set an onKeyDown event listener on the input to perform an action when a key is pressed. In this listener, we use the KeyboardEvent object’s key property to check if the key pressed is Enter, and if so, we use the ref object to get the input’s value and update the updated variable with it.

While the data in a controlled input is handled by React state, the data in an uncontrolled input is handled by the DOM itself. This is why the input in the example above doesn’t have a value prop or onChange event handler set. Instead, we access the input field value with a React ref. The DOM updates this value when the text in the input is changed.

We create a ref object with the useRef hook and set it to the ref prop of the input. Doing this sets the current property of the ref object to the DOM object that represents the input element.

useRef returns a mutable ref object that does not change value when a component is updated. Also, modifying the value of this object’s current property does not cause a re-render. This is in contrast to the setState update function returned from useState.

Although the React documentation recommends using controlled components, uncontrolled components offer some advantages. You might prefer them if the form is simple and doesn’t need instant validation, and values only need to be accessed on submission.

How to Check if a Checkbox is Checked in Vue.js

To check if a checkbox is checked in Vue:

  1. Create a boolean state variable to store the value of the checkbox.
  2. Use v-model to set up a two-way binding between the checkbox’s value and the state variable.
  3. If the checkbox is checked, the state variable will be true. Otherwise, it will be false.

For example:

App.vue

<template>
  <div id="app">
    <input
      type="checkbox"
      v-model="agreement"
      name="agreement"
    />

    <label for="agreement">
      I agree to the terms and conditions
    </label>

    <br /><br />

    <button :disabled="!agreement">Continue</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      agreement: false,
    };
  },
};
</script>
The button is disabled when the checkbox is checked, and enabled when it is unchecked.
The button is disabled when the checkbox is checked, and enabled when it is unchecked.

The checked property of the checkbox object indicates whether or not the checkbox is checked.

Every time the checkbox is checked or unchecked, the agreement state variable will be automatically updated to true or false respectively.

We set the button‘s disabled prop to the negation of agreement to disable and enable it when agreement is true and false respectively.

Check if checkbox is checked with ref

In most cases, v-model will be sufficient for checking if a checkbox if a checked in Vue. However, we can also use the ref attribute to get the input value. We can set this attribute on any DOM element and use the $refs property of the Vue instance to access the object that represents the element.

For example:

<template>
  <div id="app">
    <!-- πŸ‘‡ Set "ref" prop to create new ref -->
    <input
      type="checkbox"
      name="js"
      ref="theCheckbox"
    />

    <label for="js"> JavaScript </label>
    <br />
    <button @click="handleClick">Done</button>
    <p v-if="message">{{ message }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return { message: '' };
  },
  methods: {
    handleClick() {
      // πŸ‘‡ Access ref with "$refs" property
      if (this.$refs.theCheckbox.checked) {
        this.message = 'You know JS';
      } else {
        this.message = "You don't know JS";
      }
    },
  },
};
</script>
The checked state of the checkbox determines the message displayed when the button is clicked.
The checked state of the checkbox determines the message displayed when the button is clicked.

We set an onClick listener on the button. In this listener, we access the checkbox object using the ref, and use its checked property to determine the message that should be shown to the user when the button is clicked.

How to Push an Object to an Array in JavaScript

To push an object to an array in JavaScript, call the push() method on the array with the object as an argument, i.e., arr.push(obj). The push() method will add the element to the end of the array.

For example:

const arr = [];

const obj = { name: 'Jeff' };

// πŸ‘‡ Push object to array
arr.push(obj);

// [{ name: 'Jeff' } ]
console.log(arr);

The push() method takes an object and adds it to the end of an array.

Push object to array during initialization

If the variable is newly created just before the object is pushed (like in the previous example), you can simply place the object in between the square brackets ([]) to include it in the array as the variable is initialized:

const obj = { name: 'Jeff' };

// πŸ‘‡ Push object to array with initialization
const arr = [obj];

console.log(arr);

Push multiple objects to array

The push() method actually accepts a variable number of arguments. They are each added to the end of the array, in the order in which they are passed to push().

For example:

const arr = [];

const obj1 = { name: 'Samantha' };
const obj2 = { name: 'Chris' };
const obj3 = { name: 'Mike' };

arr.push(obj1, obj2, obj3);

// [ { name: 'Samantha' }, { name: 'Chris' }, { name: 'Mike' } ]
console.log(arr);

Push object to array without mutation

The push() method adds an object to the array in place, which means it gets modified. If you don’t want this, you can use the spread syntax (...) to create a copy of the original array, before calling push():

const arr = [{ name: 'Jerry' }];

const newArr = [...arr];

newArr.push({ name: 'Mia' });

// [ { name: 'Jerry' }, { name: 'Mia' } ]
console.log(newArr);

// πŸ‘‡ Original not modified
console.log(arr); // [ { name: 'Jerry' } ]

Similar to what we did earlier, we can include the object in the square brackets, after the spread syntax, to push the object to the array’s copy as it is initialized:

const arr = [{ name: 'Jerry' }];

// πŸ‘‡ Push object to array without mutation
const newArr = [...arr, { name: 'Mia' }];

// [ { name: 'Jerry' }, { name: 'Mia' } ]
console.log(newArr);

// Original not modified
console.log(arr); // [ { name: 'Jerry' } ]

While not always necessary, by avoiding mutations we can make our code more readable, predictable, and modular.

How to Remove a Class From Multiple Elements With JavaScript

To remove a class from multiple elements in JavaScript:

  1. Get a list of all the elements with a method like document.querySelectorAll(selector).
  2. Iterate over the list with forEach().
  3. For each element, call classList.remove(class) to remove the class from each element.

i.e.:

const elements = document.querySelectorAll('.class');

elements.forEach((element) => {
  element.classList.remove('class');
});

For example:

HTML

<p class="big bold text">Coding</p>
<p class="big bold text">Beauty</p>
<p class="big bold text">Dev</p>

<button id="remove">Remove class</button>

JavaScript

const removeBtn = document.getElementById('remove');

removeBtn.addEventListener('click', () => {
  const elements = document.querySelectorAll('.text');

  elements.forEach((element) => {
    element.classList.remove('big');
  });
});

CSS

.bold {
  font-weight: bold;
}

.big {
  font-size: 1.2em;
}

This will be the HTML after the button is clicked:

<p class="bold text">Coding</p>
<p class="bold text">Beauty</p>
<p class="bold text">Dev</p>

<button id="remove">Remove class</button>
The big class is removed from the texts when the button is clicked.
The big class is removed from the texts when the button is clicked.

We use the document.querySelectorAll() method to select all DOM elements from which we want to remove the class.

We iterate over the elements in the list object with the forEach() method. This forEach() method works similarly to Array forEach().

document.getElementsByClassName() method

We can use the document.getElementsByClassName() method in place of the document.querySelectorAll() method when the selector is a class selector. For getElementsByClassName(), we pass the class name without the . (dot), and we use Array.from() to convert the result to an array before the iteration with forEach().


const elements = Array.from(document.getElementsByClassName('text'));
elements.forEach((element) => {
  element.classList.remove('big');
});

classList.remove() method

We use the classList.remove() method to remove a class from the elements. You can remove multiple classes by passing more arguments to remove().

const elements = document.querySelectorAll('.text');

elements.forEach((element) => {
  element.classList.remove('big', 'bold');
});

If any of the classes passed to remove() doesn’t exist on the element, remove() will ignore it, instead of throwing an error.

Remove class from multiple elements with different selectors

Sometimes there is no common selector between the elements that you want to remove the class from. For such a case, you can pass multiple comma-separated selectors to the querySelectorAll() method.

const elements = document.querySelectorAll('.text, #box-1, #box-2');

elements.forEach((element) => {
  element.classList.remove('bold');
});

Add class to multiple elements

Just like the classList.remove() method removes one or more classes from an element, the classList.add() method adds one or more classes to an element. This means that we can use it in the forEach() method to remove a class from multiple DOM elements:

const elements = document.querySelectorAll('.text');
elements.forEach((element) => {
  element.classList.add('italic', 'underline');
});

How to Add Months to a Date in JavaScript

1. Date getMonth() and setMonth() methods

To add months to a Date in JavaScript:

  1. Call the getMonth() to get the number of months.
  2. Add the new months.
  3. Pass the sum to the setMonth() method.

For example:

function addMonths(date, months) {
  date.setMonth(date.getMonth() + months);

  return date;
}

// May 17, 2022
const date = new Date('2022-05-17T00:00:00.000Z');

const newDate = addMonths(date, 4);

// September 17, 2022
console.log(newDate); // 2022-09-17T00:00:00.000Z

Our addMonths() takes a Date object and the number of months to add as arguments. It returns the same Date object with the newly added months.

The Date getMonth() returns a zero-based number that represents the month of a particular date.

The Date setMonth() method sets the months of a date to a specified zero-based number.

Note: β€œZero-based” here means that 0 is January, 1 is February, 2 is March, etc.

If the months added would increase the year of the Date, setMonth() will automatically update the information in the Date object to reflect this.

// November 12, 2022
const date = new Date('2022-11-12T00:00:00.000Z');

date.setMonth(date.getMonth() + 3);

// February 12, 2023
console.log(date); // 2023-02-12T00:00:00.000Z

Here we added 3 months to a date in November 2022. This makes setMonth() automatically update the year to 2023.

Avoid side effects

The setMonth() method mutates the Date object it is called on. This introduces a side effect in our addMonths() function. To avoid modifying the passed Date and create a pure function, make a copy of the Date and call setMonth() on this copy, instead of the original.

function addMonths(date, months) {
  // πŸ‘‡ Make copy with "Date()" constructor
  const dateCopy = new Date(date);

  dateCopy.setMonth(dateCopy.getMonth() + months);

  return dateCopy;
}

// August 16, 2022
const date = new Date('2022-08-16T00:00:00.000Z');

const newDate = addMonths(date, 3);

// November 16, 2022
console.log(newDate); // 2022-11-16T00:00:00.000Z

// πŸ‘‡ Original not modified
console.log(date); // 2022-08-16T00:00:00.000Z

Tip: Functions that don’t modify external state (i.e., pure functions) tend to be more predictable and easier to reason about, as they always give the same output for a particular input. This makes it a good practice to limit the number of side effects in your code.

2. date-fns addMonths() function

Alternatively, we can use the addMonths() function from the date-fns library to quickly add months to a Date. It works like our pure addMonths() function.

import { addMonths } from 'date-fns';

// July 14, 2022
const date = new Date('2022-07-14T00:00:00.000Z');

const newDate = addMonths(date, 1);

// August 14, 2022
console.log(newDate); // 2022-08-14T00:00:00.000Z

// Original not modified
console.log(date); // 2022-07-14T00:00:00.000Z

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.

How to Convert CSV to JSON in JavaScript

You can use the csvtojson library to quickly convert CSV to JSON in JavaScript:

index.js

index.js
import csvToJson from 'csvtojson'; const csvFilePath = 'data.csv'; const json = await csvToJson().fromFile(csvFilePath); const jsonString = JSON.stringify(json, null, 2) console.log(jsonString);

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 JSON:

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

We use csvtojson to convert the CSV into a JSON object, and use the JSON.stringify() method to convert the object into a well-formatted JSON string.

Install csvtojson

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

Shell
npm i csvtojson # Yarn yarn add csvtojson

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

JavaScript
import csvToJson from 'csvtojson'; // CommonJS const csvToJson = require('csvtojson');

Convert CSV file to JSON with fromFile()

We call the default export function of the csvtojson module to create the object that will convert the CSV. This object has a bunch of methods, each related in some way to the conversion of CSV to JSON, 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 JSON 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 json = await csvToJson().fromString(csv); const jsonString = JSON.stringify(json, null, 2); console.log(jsonString); ο»Ώ
JSON
[ { "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 JSON

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 json = await csvToJson({ headers: ['firstName', 'lastName', 'age'], }).fromString(csv); console.log(json);
JSON
[ { "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:

index.js
import csvToJson from 'csvtojson'; const csv = `"First Name"|"Last Name"|"Age" "Russell"|"Castillo"|23 "Christy"|"Harper"|35 "Eleanor"|"Mark"|26`; const json = await csvToJson({ headers: ['firstName', 'lastName', 'age'], delimiter: '|', }).fromString(csv); const jsonString = JSON.stringify(json, null, 2); console.log(jsonString);
JSON
[ { "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.

index.js
import csvToJson from 'csvtojson'; const csv = `"First Name"|"Last Name"|"Age" "Russell"|"Castillo"|23 "Christy"|"Harper"|35 "Eleanor"|"Mark"|26`; const json = await csvToJson({ headers: ['firstName', 'lastName', 'age'], delimiter: '|', ignoreColumns: /lastName/, }).fromString(csv); const jsonString = JSON.stringify(json, null, 2); console.log(jsonString);
JSON
[ { "firstName": "Russell", "age": "23" }, { "firstName": "Christy", "age": "35" }, { "firstName": "Eleanor", "age": "26" } ]

Convert CSV to JSON 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 json = await csvToJson({ output: 'csv', }).fromString(csv); const jsonString = JSON.stringify(json, null, 2); console.log(jsonString);
JSON
[ [ "red", "120", "2" ], [ "blue", "100", "3" ], [ "green", "130", "2" ] ]

Native conversion of CSV to JSON

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

index.js
function csvToJson(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 result; } const csv = `color,maxSpeed,age red,120,2 blue,100,3 green,130,2`; const json = csvToJson(csv); const jsonString = JSON.stringify(json, null, 2); console.log(jsonString);

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

Output:

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