Convert Form Data to JavaScript Object

Introduction

When working with forms in JavaScript, you'll typically need to convert form data to a JavaScript object (JSON) in order to populate an array, database, local storage, send it to an API, or even consume the data in your application. Conversion between form data and JSON is one of the most common ways to process form data as it opens doors to a plethora of other uses for that data.

In this article, we'll take a look at how to easily convert form data into a JavaScript object without installing any unnecessary dependencies. We'll achieve that just by using the FormData API - a built-in browser API used to get form values as JavaScript objects.

Note: This app is available as a demo on CodePen.

Let's get started by creating a simple HTML form containing several common form fields - two input fields, a text area, and a submit button:

<form>
    <div class="form-control">
        <label for="name">Full Name</label>
        <input id="name" name="name" type="text" />
    </div>
    <div class="form-control">
        <label for="email">Email Address</label>
        <input id="email" name="email" type="email" />
    </div>
    <div class="form-control">
        <label for="message">Enter a Message</label>
        <textarea id="message" name="message" rows="6" cols="65"></textarea>
    </div>
    <button class="btn" type="submit">Send</button>
</form>

Now, we can take a look at how to convert its data into JSON (JavaScript Object Notation) using FormData API.

FormData API

FormData is a built-in browser API that provides us a way to easily access any field from a HTML form. The first step in using FormData API is to obtain the form element using some of the appropriate HTML DOM methods - document.querySelector() or document.getElementById(). After that, we can add an event listener that calls callbackFunction when it registers a submit event on the form:

const form = document.getElementById('contact-form');

form.addEventListener('submit', callbackFunction);

For the event listener to work, we must define the function that will handle the submit event. For now, let's just make it create the FormData object and log its content into console:

function callbackFunction(event) {
    event.preventDefault();
    const myFormData = new FormData(event.target);
    console.log(myFormData);
}

Note: We used the preventDefault() to prevent the form from reloading after the submit button is clicked - which is the default behavior. This is a sensible default, but for the sake of illustration in our app - we'll prevent it and display the data on the right-hand div.

When you run the code above, the result will be an empty object, which is not what we've expected:

FormData {}

Even though it may seem like we've created an empty object, that is not the case. That FormData object has a key-value pair for each field in our form - therefore, we need to iterate over all those pairs and store them in a separate object. After that, we can use that object to access each individual field of our form.

There are two major ways we can get data from the FormData API - one is to loop through every key-value pair, and the other is to use the Object.fromEntries() method.

How to Convert Form Data to JSON With Loops

The first way to create a readable object from a FormData object is to iterate over its key-value pairs and manually add keys and values to the newly created object. For the purpose of this article, we'll use the forEach() loop in JavaScript. First of all, we'll create an empty object and then iterate over the FormData object we've created in the previous section:

const formDataObj = {};
myFormData.forEach((value, key) => (formDataObj[key] = value));

Note: The forEach() method is not async friendly, if you need your callback function to support async calls - you should use the for-of loop.

At this point we can modify the callbackFunction() from the previous section so that it correctly outputs the form data as an object:

const form = document.getElementById('contact-form');

form.addEventListener('submit', callbackFunction);
                      
function callbackFunction(event) {
    event.preventDefault();
    const myFormData = new FormData(event.target);

    const formDataObj = {};
    myFormData.forEach((value, key) => (formDataObj[key] = value));
    console.log(formDataObj);
});

Now, when we fill out our form and click the submit button we should have the following output:

{
    "name": "John Doe",
    "email": "[email protected]",
    "message": "Hello World"
}
Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

This object has field names as its keys and corresponding field values as its values.

How to Convert Form Data to JSON With Object.fromEntries()

Alternatively, we can use the Object.fromEnteries() method instead of loops to retrieve form fields from the FormData object. That way we don't need to create an empty object before we start - the method allows us to directly convert the FormData object to the corresponding JavaScript object:

const formDataObj = Object.fromEntries(myFormData.entries());

At this point, our modified callback function will look like this:

const form = document.getElementById('contact-form');

form.addEventListener('submit', callbackFunction);
function callbackFunction(event) {
    event.preventDefault();
    const myFormData = new FormData(event.target);

    const formDataObj = Object.fromEntries(myFormData.entries());
    console.log(formDataObj);
});

An object populated using Object.fromEnteries() will have names of the form fields as its keys and corresponding form values as its values:

{
    "name": "John Doe",
    "email": "[email protected]",
    "message": "Hello World"
}

Note: For both methods, we can use JSON.stringify() to convert the object into a JSON string, which we can then use to send JSON encoded data to APIs.

How to Get Multiple Selected Values in JSON With The FormData API

The above methods are compatible with almost all form fields - input text, number, radio, select... However, there are other fields that can be a bit more tricky to work with. The most notable one is the checkbox - it allows multiple values to be selected. But the previously shown methods will replace all of those selected values with just one - which is ultimately stored in the resulting object. Let's take a look at how to solve that and store all selected values in the resulting object. Suppose we have an HTML form with a checkbox field:

<!-- -->

<div class="form-control-2">
    <p class="group-label">Your favorite pet:</p>
    <input type="checkbox" name="favorite_pet" value="Cats" />Cats
    <input type="checkbox" name="favorite_pet" value="Dogs" />Dogs
    <input type="checkbox" name="favorite_pet" value="Birds" />Birds
</div>

<!-- -->

We can get all the selected data into an array using the getAll() method on the FormData object:

formDataObj.favorite_pet = myFormData.getAll('favorite_pet');

At this point, our code will look something like this:

const form = document.getElementById('contact-form');

form.addEventListener('submit', callbackFunction);
function callbackFunction(event) {
    event.preventDefault();
    const myFormData = new FormData(event.target);

    const formDataObj = Object.fromEntries(myFormData.entries());
    formDataObj.favorite_pet = myFormData.getAll('favorite_pet');
    console.log(formDataObj);
});

And the populated object will contain an array of values a user selected in the checkbox field:

{
    "name": "uhuk",
    "email": "[email protected]",
    "message": "jgghhjb",
    "favorite_pet": [
        "Cats",
        "Birds"
    ]
}

Note: You can check out this live demo on CodePen which uses all the major form field types and generates the data as a JavaScript object when submitted.

Conclusion

In this article, we've taken a look at how to use the FormData API to convert form data to JavaScript objects without any additional dependencies. We've also learned how to correctly handle various types of form fields (inputs, text-areas, etc.), as well as some trickier ones such as checkboxes.

Last Updated: June 26th, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Joel OlawanleAuthor

Frontend Developer & Technical Writer

Project

React State Management with Redux and Redux-Toolkit

# javascript# React

Coordinating state and keeping components in sync can be tricky. If components rely on the same data but do not communicate with each other when...

David Landup
Uchechukwu Azubuko
Details

Getting Started with AWS in Node.js

Build the foundation you'll need to provision, deploy, and run Node.js applications in the AWS cloud. Learn Lambda, EC2, S3, SQS, and more!

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms