Created
July 27, 2017 08:34
-
-
Save faridv/cdefe4a97c1fb12cf03b0d6e04789ecd to your computer and use it in GitHub Desktop.
jQuery plugin to serialize form as an object (also using underscore.js)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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; | |
}, {}); | |
}; |
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
Pure jQuery version (no underscore/lodash code)