Last week, we looked at how to serialize form data into an array in vanilla JS. Today, we'll do something really similar: we'll learn how to put the data into an object instead of an array.
Because it's so similar, I'll just show you the complete function:
/**
* Serialize all form data into an object
* @param {HTMLFormElement} form The form to serialize
* @returns {Object} The serialized form data
*/
function serializeObject (form) {
// Create a new FormData object
const formData = new FormData(form);
// Create an object to hold the name/value pairs
const pairs = {};
// Add each name/value pair to the object
for (const [name, value] of formData) {
pairs[name] = value;
}
// Return the object
return pairs;
}
The only difference is that we:
- Created an object literal instead of an array literal; and
- Set properties on the object instead of pushing elements into an array.
As with last week's helper function, this solution makes use of several ES6 features including the const
keyword, a for...of
loop, and destructuring assignment. It should work in all modern browsers, but not IE. It's available under the MIT license, so feel free to use it in your own projects: serializeObject.js.
If you need better browser support, my friend Chris Ferdinandi has an alternative version that should work back to IE9.