Skip to content

Instantly share code, notes, and snippets.

@faridv
Created July 27, 2017 08:34
Show Gist options
  • Save faridv/cdefe4a97c1fb12cf03b0d6e04789ecd to your computer and use it in GitHub Desktop.
Save faridv/cdefe4a97c1fb12cf03b0d6e04789ecd to your computer and use it in GitHub Desktop.
jQuery plugin to serialize form as an object (also using underscore.js)
"use strict";
$.fn.serializeObject = function () {
var arr = this.serializeArray();
return _.reduce(arr, function (memo, f) {
var objField = _.reduceRight(f.name.replace(/\[/g, ".").replace(/\]/g, "").split("."), function (memo, p) {
var n = (/^[0-9]+$/.test(p)) ? [] : {};
n[p] = memo;
return n;
}, f.value);
$.extend(true, memo, objField);
return memo;
}, {});
};
@faridv
Copy link
Author

faridv commented Aug 19, 2020

Pure jQuery version (no underscore/lodash code)

$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
	if (o[this.name] !== undefined) {
	    if (!o[this.name].push) {
		o[this.name] = [o[this.name]];
	    }
	    o[this.name].push(this.value || '');
	} else {
	    o[this.name] = this.value || '';
	}
    });
    return o;
};

@faridv
Copy link
Author

faridv commented Aug 19, 2020

serializeObject

Serialize form as an object instead of default string

Usage

Instead of jQuery serialize method which is widely used on forms, you can alternatively use current jQuery plugin and do something like this:

$(function(){
  var obj = $("form").serializeObject();
});

You can use it in RESTful structures which only accept objects of parameters.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment