How to Convert a JavaScript Object to a Form Data in JavaScript?
Last Updated :
06 Sep, 2024
In web development, especially when dealing with forms and AJAX requests, you might find yourself needing to convert a JavaScript object into a FormData object. The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be sent via XMLHttpRequest or fetch() to the server.
What is FormData?
FormData is a web API that allows you to create a set of key/value pairs representing form fields and their values. This is particularly useful when you need to send form data to a server using AJAX, or when dealing with file uploads. Each pair in the FormData object is stored as a key-value pair.
Why Convert a JavaScript Object to FormData?
There are several scenarios where converting a JavaScript object to FormData is necessary:
- File Uploads: When you need to upload files along with other form data.
- Multipart/Form-Data Requests: When interacting with APIs that require data to be sent in multipart/form-data format.
- Complex Forms: When dealing with complex forms where you want to manage data as a JavaScript object before sending it to the server.
Approach For Converting To Form Data
The conversion process involves iterating over the object’s properties and appending them to a FormData instance. Below is a step-by-step guide on how to do this.
Step 1: Create the JavaScript Object:
First, you need a JavaScript object that you want to convert. This object can contain various data types, including strings, numbers, and even files.
const data = {
name: 'John Doe',
age: 30,
occupation: 'Developer',
profileImage: document.querySelector('input[type="file"]').files[0]
};
Step 2: Initialize the FormData Object
Next, you need to create an instance of the FormData object. This object will store the key-value pairs that you will append from your JavaScript object.
const formData = new FormData();
Step 3: Append Key-Value Pairs to FormData
Now, you can loop through the JavaScript object and append each key-value pair to the FormData instance. You can use a for...in loop to iterate over the object’s properties.
for (const key in data) {
if (data.hasOwnProperty(key)) {
formData.append(key, data[key]);
}
}
In this code snippet:
- We loop through the data object.
- For each key-value pair, we check if the property is directly on the object using hasOwnProperty.
- We then append the key and its corresponding value to the FormData object.
Step 4: Sending the FormData
Once your FormData object is populated, you can send it using XMLHttpRequest, fetch(), or any other method that supports multipart form data.
Using Fetch API:
fetch('/upload', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Or using XMLHttpRequest:
const xhr = new XMLHttpRequest();
xhr.open('POST', '/upload', true);
xhr.send(formData);
Step 5: Handling Nested Objects
If your JavaScript object contains nested objects, the basic approach outlined above will not work as intended. To handle nested objects, you would need to implement a recursive function to flatten the object structure before appending it to the FormData object.
In this approach, appendFormData is a recursive function that flattens the object hierarchy by appending keys in a bracket notation format, which is common in PHP and other backend frameworks for parsing nested structures.
function appendFormData(formData, data, parentKey = '') {
for (const key in data) {
if (data.hasOwnProperty(key)) {
const formKey = parentKey ? `${parentKey}[${key}]` : key;
if (typeof data[key] === 'object' && !(data[key] instanceof File)) {
appendFormData(formData, data[key], formKey);
} else {
formData.append(formKey, data[key]);
}
}
}
}
const formData = new FormData();
appendFormData(formData, data);
Example: Here is the full script that you can run directly in a browser's console or in a Node.js environment (with slight modifications for Node.js):
JavaScript
const data = {
name: 'John Doe',
age: 30,
occupation: 'Developer',
};
const formData = new FormData();
for (const key in data) {
if (data.hasOwnProperty(key)) {
formData.append(key, data[key]);
}
}
for (let pair of formData.entries()) {
console.log(pair[0] + ': ' + pair[1]);
}
Output: Create a file named a.js in your project directory and run :
node a.js
Convert a JavaScript Object to a Form Data in JavaScript
Similar Reads
How to convert form data to JavaScript object with jQuery ?
JavaScript objects are complex data types that can store multiple values and properties. Unlike primitive data types that only hold a single value, objects can hold various data types, including other objects, arrays, functions, and more. The inputs given by a user can be converted into objects wher
3 min read
How to Convert JavaScript Class to JSON in JavaScript?
When transmitting or saving class data in a structured manner, converting an instance of a class into a JSON format is also necessary. JSON (JavaScript Object Notation) supplies a method of turning objects into strings. They can be sent across a network or stored in a database, properties of the ins
2 min read
How to Convert JSON Object to CSV in JavaScript ?
JSON (JavaScript Object Notation) and CSV (Comma-Separated Values) are two widely used formats, each with its own strengths and applications. Fortunately, JavaScript provides powerful tools to facilitate the conversion process between these formats. These are the following approaches: Table of Conte
3 min read
How to Convert an Array of Objects to Map in JavaScript?
Here are the different methods to convert an array of objects into a Map in JavaScript 1. Using new Map() ConstructorThe Map constructor can directly create a Map from an array of key-value pairs. If each object in the array has a specific key-value structure, you can map it accordingly. [GFGTABS] J
4 min read
How to Convert Blob Data to JSON in JavaScript ?
When dealing with Blob data in JavaScript, such as binary data or files, we may need to convert it into JSON format for doing so JavaScript provides us with various methods as listed below. Table of Content Using FileReader APIUsing TextDecoder APIUsing FileReader APIIn this approach, we first use t
2 min read
How to check a JavaScript Object is a DOM Object ?
Checking if a JavaScript object is a DOM object involves verifying whether the object represents an element or component within the Document Object Model (DOM) of an HTML or XML document. This can be done by checking if the object is an instance of Node, Element, or other specific DOM interfaces. Wh
2 min read
How to Convert an Object into Array of Objects in JavaScript?
Here are the different methods to convert an object into an array of objects in JavaScript 1. Using Object.values() methodObject.values() method extracts the property values of an object and returns them as an array, converting the original object into an array of objects. [GFGTABS] JavaScript const
3 min read
How to Store an Object Inside an Array in JavaScript ?
Storing an object inside an array in JavScript involves placing the object as an element within the array. The array becomes a collection of objects, allowing for convenient organization and manipulation of multiple data structures in a single container. Following are the approaches through which it
3 min read
How to Convert HTML Form Field Values to JSON Object using JavaScript?
Storing HTML input data into JSON format using JavaScript can be useful in various web development scenarios such as form submissions, data processing, and AJAX requests. Here we will explore how to convert the HTML form input data into the JSON format using JavaScript. ApproachThe HTML file contain
2 min read
How to Convert CSV to JSON in JavaScript ?
In this article, we will explain different ways to change Comma-Separated Values (CSV) data into JavaScript Object Notation (JSON) format, step-by-step. We'll break down each method with clear explanations and examples. There are several approaches available in JavaScript to convert CSV to JSON in J
3 min read