Explain Codes LogoExplain Codes Logo

Convert form data to JavaScript object with jQuery

javascript
prompt-engineering
functions
callbacks
Nikita BarsukovbyNikita Barsukov·Oct 6, 2024
TLDR

To convert form data to a JavaScript object with jQuery, you can use the .serializeArray() method. Here is a succinct way of doing that:

var formObject = {}; $.each($('#yourFormId').serializeArray(), function() { formObject[this.name] = this.value; });

This code conveniently iterates through your form data and constructs an object (formObject). In this object, the form field names act as keys and their corresponding values as the values for the keys. You only need to replace #yourFormId with your specific form ID.

Dealing with simpler fields

The .serializeArray() method provides a jQuery routine to conveniently map each form field to a corresponding JavaScript object property.

Use .reduce() for efficiency

A more efficient approach is to invoke the .reduce() method as follows:

var formObject = $('#yourFormId').serializeArray().reduce(function(obj, item) { if (!obj[item.name]) { obj[item.name] = item.value; // Pretty straightforward, right? } else if (Array.isArray(obj[item.name])) { obj[item.name].push(item.value); // Chuck it in if it's an array } else { // Now this is where the fun starts! obj[item.name] = [obj[item.name], item.value]; // Hello world, meet multi-value fields! } return obj; }, {});

The above code easily handles fields with the same name, bundling them into an array. This comes handy while dealing with checkboxes or select options where multiple selections can be made.

For complex forms: Improvise, Adapt, Overcome!

For complex forms using nested objects and arrays, extend your approach like so:

function objectifyForm(formArray) { var returnArray = {}; for (var i = 0; i < formArray.length; i++){ var field = formArray[i]; if (field.name.indexOf('[') > -1 && field.name.indexOf(']') > -1) { var names = field.name.split('['); var name = names[0]; var subName = names[1].slice(0, -1); // Snip, snip! if (!returnArray[name]) { returnArray[name] = {}; // Create fresh if doesn't exist } if (subName.length > 0) { returnArray[name][subName] = field.value; // Assoc array } else { if (!Array.isArray(returnArray[name])) { returnArray[name] = []; // Create fresh if doesn't exist } returnArray[name].push(field.value); // The more, the merrier } } else { returnArray[field.name] = field.value; // Business as usual } } return returnArray; } var formObject = objectifyForm($('#yourFormId').serializeArray());

This allows jQuery's .serializeArray() results to be expanded to nested arrays and objects. Talk about highly structured data to work with!