Download Convert Form Data to JavaScript Object - JavaScript
Categories:Viewed: 47 - Published at: 4 months ago

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.

handle parse and convert form data into a javascript object or json

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 form 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 righ-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&nbsp;protected]",
    "message": "Hello World"
}

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&nbsp;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.
        <h3 id="howtogetmultipleselectedvaluesinjsonwiththeformdataapi">How to Get Multiple Selected Values in JSON With The FormData API</h3>

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">
    Your favourite pet:
    <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&nbsp;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.
        <h3 id="conclusion">Conclusion</h3>

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, textareas, etc.), as well as some trickier ones such as checkboxes.

Reference: stackabuse.com

TAGS :