Bisexual Pride

Last week, I wrote about a vanilla JS alternative to the jQuery serialize() method. Well, jQuery also provides a serializeArray() method, so let’s create a helper function for that too.

First things first, let’s create our function declaration and set up our JSDoc block:

/**
* Serialize all form data into an array
* @param {HTMLFormElement} form The form to serialize
* @returns {Array} The serialized form data
*/

function serializeArray (form) {}

As with our serialize() helper function, the first thing we need to do is create a FormData object using the desired HTMLFormElement. This makes it trivial for us to manipulate the form data:

/**
* Serialize all form data into an array
* @param {HTMLFormElement} form The form to serialize
* @returns {Array} The serialized form data
*/

function serializeArray (form) {
// Create a new FormData object
const formData = new FormData(form);
}

Next, we need to create an array of name/value pairs. We’ll create an array literal and then use a for...of loop to append each object:

/**
* Serialize all form data into an array
* @param {HTMLFormElement} form The form to serialize
* @returns {Array} The serialized form data
*/

function serializeArray (form) {
// Create a new FormData object
const formData = new FormData(form);

// Create an array to hold the name/value pairs
const pairs = [];

// Add each name/value pair to the array
for (const [name, value] of formData) {
pairs.push({ name, value });
}
}

Finally, we just need to return the array:

/**
* Serialize all form data into an array
* @param {HTMLFormElement} form The form to serialize
* @returns {Array} The serialized form data
*/

function serializeArray (form) {
// Create a new FormData object
const formData = new FormData(form);

// Create an array to hold the name/value pairs
const pairs = [];

// Add each name/value pair to the array
for (const [name, value] of formData) {
pairs.push({ name, value });
}

// Return the array
return pairs;
}

This solution makes use of several ES6 features including the const keyword, a for...of loop, destructuring assignment, and shorthand property names. 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: serializeArray.js.

If you need better browser support, my friend Chris Ferdinandi has an alternative version that should work back to IE9.

View the demo on CodePen