NeuroAgent

How to Convert Form Elements to JavaScript Object with jQuery

Learn how to convert jQuery form elements to JavaScript objects using plugins like serializeObject and serializeJSON. Avoid string and array formats with this complete guide.

Question

How do I convert all form elements to a JavaScript object using jQuery?

I’m looking for a way to automatically build a JavaScript object from my form elements without manually iterating through each element. I specifically don’t want the string format returned by $(‘#formid’).serialize() or the array format returned by $(‘#formid’).serializeArray(). How can I achieve this conversion?

NeuroAgent

You can convert form elements to a JavaScript object using jQuery by utilizing plugins like serializeObject or serializeJSON, which transform form data into structured objects rather than the string format from .serialize() or the array format from .serializeArray(). These plugins automatically handle nested attributes, arrays, and complex form structures without requiring manual element iteration.

Contents

Built-in jQuery Methods

While jQuery doesn’t have a built-in method that directly converts form elements to a JavaScript object, understanding the available methods helps contextualize the solution:

.serialize() Method

  • Returns form data as URL-encoded string
  • Example: $('#myform').serialize()"name=John&email=john%40example.com&age=30"

.serializeArray() Method

  • Returns form data as array of objects
  • Example: $('#myform').serializeArray()[{name: "name", value: "John"}, {name: "email", value: "john@example.com"}, {name: "age", value: "30"}]

According to the jQuery API documentation, the .serializeArray() method “creates a JavaScript array of objects, ready to be encoded as a JSON string” but doesn’t directly convert to the desired object format.

Using serializeObject Plugin

The jquery-serialize-object plugin is one of the most popular solutions for converting form data to JavaScript objects.

Installation

html
<script src="https://code.jquery.com/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-serialize-object/2.5.0/jquery.serializeobject.min.js"></script>

Basic Usage

javascript
$('#myform').serializeObject();
// Returns: {name: "John", email: "john@example.com", age: "30"}

Features

  • Automatically converts form data to nested objects
  • Handles array inputs with proper indexing
  • Supports disabled form elements
  • No additional configuration needed

Example with Nested Structure

html
<form id="contact">
    <input name="user[email]" value="jsmith@example.com">
    <input name="user[pets][]" type="checkbox" value="cat" checked>
    <input name="user[pets][]" type="checkbox" value="dog" checked>
    <input name="user[pets][]" type="checkbox" value="bird">
    <input type="submit">
</form>
javascript
$('#contact').serializeObject();
// Returns: 
// {
//   user: {
//     email: "jsmith@example.com",
//     pets: ["cat", "dog"]
//   }
// }

Using serializeJSON Plugin

For more complex scenarios, the jquery-serializeJSON plugin offers advanced features for nested structures and arrays.

Installation

html
<script src="https://code.jquery.com/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-serializejson@3.0.1/jquery.serializejson.min.js"></script>

Usage

javascript
$('#myform').serializeJSON();
// Returns the same object structure as serializeObject

Advanced Features

  • Supports nested attributes using dot notation
  • Handles arrays automatically
  • Custom value parsing functions
  • Date and number type conversion
html
<form id="complex-form">
    <input name="user.name" value="John">
    <input name="user.email" value="john@example.com">
    <input name="user.age" type="number" value="30">
    <input name="user.preferences.theme" value="dark">
    <input name="user.preferences.language" value="en">
    <input name="tags[]" value="javascript" type="checkbox" checked>
    <input name="tags[]" value="jquery" type="checkbox" checked>
</form>
javascript
$('#complex-form').serializeJSON();
// Returns:
// {
//   user: {
//     name: "John",
//     email: "john@example.com",
//     age: 30, // Number type
//     preferences: {
//       theme: "dark",
//       language: "en"
//     }
//   },
//   tags: ["javascript", "jquery"]
// }

Manual Conversion Approaches

If you prefer to avoid plugins, several manual approaches can convert form arrays to objects:

Using Object.fromEntries()

javascript
const formData = Object.fromEntries(
  $('#myform').serializeArray().map(item => [item.name, item.value])
);

Using jQuery.reduce()

javascript
const formData = $('#myform').serializeArray().reduce((obj, item) => {
  obj[item.name] = item.value;
  return obj;
}, {});

Using Underscore.js _.map()

javascript
const formData = _( $('#myform').serializeArray() ).reduce((memo, pair) => {
  memo[pair.name] = pair.value;
  return memo;
}, {});

Each of these approaches provides the same basic functionality but may require additional code for handling nested structures and arrays.

Advanced Features and Considerations

Handling Disabled Elements
The standard serialize() and serializeArray() methods exclude disabled form elements. To include them:

javascript
const formData = $('#myform').find(':input:enabled, :input:disabled').serializeArray();

Type Conversion
Plugin solutions often include automatic type conversion:

javascript
// With serializeJSON, numbers remain as numbers
$('#numeric-form').serializeJSON();
// { age: 30, price: 19.99 }

Custom Selectors
You can serialize only specific form elements:

javascript
// Only text and select inputs
const formData = $('#myform').find('input[type="text"], select').serializeObject();

File Input Support
Some plugins handle file inputs with FileReader API:

javascript
// Example from Aleksandr-ru/serializeObject
$('form').on('submit', function(e) {
  e.preventDefault();
  $(this).serializeObject().done(function(o) {
    console.log(o); // Object with file data
  }).fail(function(e) {
    // Handle FileReader error
  });
});

Practical Examples

Contact Form Example

html
<form id="contact-form">
    <div>
        <label>Name:</label>
        <input type="text" name="name" value="John Doe">
    </div>
    <div>
        <label>Email:</label>
        <input type="email" name="email" value="john@example.com">
    </div>
    <div>
        <label>Message:</label>
        <textarea name="message">Hello World</textarea>
    </div>
    <div>
        <label>Category:</label>
        <select name="category">
            <option value="general" selected>General</option>
            <option value="support">Support</option>
            <option value="feedback">Feedback</option>
        </select>
    </div>
    <button type="submit">Submit</button>
</form>
javascript
// Using serializeObject
$('#contact-form').on('submit', function(e) {
    e.preventDefault();
    const formData = $(this).serializeObject();
    console.log(formData);
    // {name: "John Doe", email: "john@example.com", message: "Hello World", category: "general"}
    
    // Send as JSON
    $.ajax({
        url: '/api/contact',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(formData),
        success: function(response) {
            console.log('Success:', response);
        }
    });
});

E-commerce Cart Example with Nested Data

html
<form id="cart-form">
    <input name="customer.name" value="Alice">
    <input name="customer.email" value="alice@example.com">
    <input name="items[0].id" value="123">
    <input name="items[0].name" value="Product A">
    <input name="items[0].quantity" value="2">
    <input name="items[0].price" value="19.99">
    <input name="items[1].id" value="456">
    <input name="items[1].name" value="Product B">
    <input name="items[1].quantity" value="1">
    <input name="items[1].price" value="29.99">
    <input name="shipping.address" value="123 Main St">
    <input name="shipping.city" value="New York">
    <input name="payment.method" value="credit_card">
    <button type="submit">Checkout</button>
</form>
javascript
$('#cart-form').on('submit', function(e) {
    e.preventDefault();
    const cartData = $(this).serializeJSON();
    console.log(cartData);
    // {
    //   customer: {name: "Alice", email: "alice@example.com"},
    //   items: [
    //     {id: "123", name: "Product A", quantity: "2", price: "19.99"},
    //     {id: "456", name: "Product B", quantity: "1", price: "29.99"}
    //   ],
    //   shipping: {address: "123 Main St", city: "New York"},
    //   payment: {method: "credit_card"}
    // }
});

Sources

  1. jQuery serializeArray() API Documentation
  2. GitHub - macek/jquery-serialize-object
  3. GitHub - marioizquierdo/jquery.serializeJSON
  4. Convert form data to JavaScript object with jQuery - Stack Overflow
  5. Serialize Form Data To JavaScript Objects - jQuery serializeObject
  6. jQuery serializeJSON Plugin - npm

Conclusion

Converting form elements to JavaScript objects using jQuery is easily achieved through specialized plugins like serializeObject and serializeJSON. These solutions automatically handle the complex data transformation that manual methods would require extensive code for. For most use cases, the serializeObject plugin provides a straightforward solution, while serializeJSON offers more advanced features like nested object support and automatic type conversion. When considering which approach to use, evaluate your specific needs for nested data structures, array handling, and type conversion requirements. Both plugins maintain the simplicity of jQuery while providing the object format you need for modern web applications.