- FormData
- Last updated on
Serializing FormData
You might intend to pass your FormData object along to an API.
While some APIs will accept a FormData object in its native form, many require you to pass along data in a different format.
Serializing FormData into an object
If your form does not contain multiple fields with the same name, you can use the Object.fromEntries() method to convert your FormData object into a plain object ({}).
// returns...
// {
// title: "Go to the beach",
// body: "Soak up the sun and swim in the ocean",
// id: "1"
// }
let serialized = Object.fromEntries(data);
However, if your form has multiple fields with the same name, only the value of the last field with that name will appear in the object.
We instead need to loop through each entry with a for...of loop and add it to an object.
let obj = {};
for (let [key, value] of data) {
obj[key] = value;
}
To account for multiple fields with the same name, we need to check if the key already exists in the obj.
If it does, we want to convert it to an array and Array.push() the new value into it.
let obj = {};
for (let [key, value] of data) {
if (obj[key] !== undefined) {
if (!Array.isArray(obj[key])) {
obj[key] = [obj[key]];
}
obj[key].push(value);
} else {
obj[key] = value;
}
}
If you find yourself doing this often, I’ve put together a helper method you can use.
/*!
* Serialize all form data into an object
* (c) 2021 Chris Ferdinandi, MIT License, https://gomakethings.com
* @param {FormData} data The FormData object to serialize
* @return {String} The serialized form data
*/
function serialize (data) {
let obj = {};
for (let [key, value] of data) {
if (obj[key] !== undefined) {
if (!Array.isArray(obj[key])) {
obj[key] = [obj[key]];
}
obj[key].push(value);
} else {
obj[key] = value;
}
}
return obj;
}
Once you have your object, you can pass it into the JSON.stringify() method to send along to an API.
let obj = serialize(data);
let stringified = JSON.stringify(obj);
Try it! When the form is submitted, convert the FormData() into an object.
Serializing FormData into a query string
Some APIs instead require data as a query string.
let str = 'key=some+value&another-key=some+other+value';
To convert our FormData object into a query string, we’ll use the URLSearchParams API.
It provides methods for getting, setting, and modifying query string values, and has a similar API as the FormData object.
First, we’ll use the new URLSearchParams() constructor to create our query string object.
let params = new URLSearchParams();
Next, we’ll loop through each item in our FormData object with a for...of loop, and use the URLSearchParams.append() method to add the key and val to our query string.
The URLSearchParams.append() method automatically encodes the value for us.
for (let [key, val] of data) {
params.append(key, val);
}
Finally, we can use the URLSearchParams.toString() method to get the actual query string.
let str = params.toString();
Try it! When the form is submitted, convert the FormData() into a query string.