Get form data as an object using jQuery

jQuery has an inbuilt method serializeArray which returns the form data in the form of an array. But at times, we require the data in form of an object. For example, consider the following form:

<form id="myForm">
    <input type="text" name="firstName" value="John">
    <input type="text" name="lastName" value="Doe">
    <input type="email" name="email" value="[email protected]">
</form>

Now $('#myForm').serializeArray() would result in the following:

[
    {
        name:"firstName",
        value:"John"
    },
    {
        name:"lastName",
        value:"Doe"
    },
    {
        name:"email",
        value:"[email protected]"
    }
]

But sometimes we require it as an object:

{
    firstName : "John",
    lastName :"Doe",
    email : "[email protected]"
}

I know we can iterate over the serialized array and create the object but wouldn’t it be great if jQuery had this functionality built in?

I made a simple script that can be used to add this functionatily to jQuery:

jQuery.fn.serializeObject = function(){
    var results = {},
        arr = this.serializeArray();
    for (var i = 0, len = arr.length; i < len; i++) {
      obj = arr[i];
      //Check if results have a property with given name
      if (results.hasOwnProperty(obj.name)) {
        //Check if given object is an array
        if (!results[obj.name].push) {
          results[obj.name] = [results[obj.name]];
        }
        results[obj.name].push(obj.value || '');
      } else {
        results[obj.name] = obj.value || '';
      }
    }
    return results;
}

usage: $('#myForm').serializeObject()

Note: The reason behind using serialzeArray inside our snippet, despite the overhead is that it already handles multiselect(s) and checkboxes robustly, thus making our job easier.

Leave a Reply