Skip to content

Instantly share code, notes, and snippets.

@bordoni
Created February 15, 2012 19:26
Show Gist options
  • Save bordoni/1838327 to your computer and use it in GitHub Desktop.
Save bordoni/1838327 to your computer and use it in GitHub Desktop.
Input Names to Object JS
$.fn.serializeObject = function() {
var _POST = [],
obj = {},
nameList = this.serializeArray(),
build = function ( hierarchy, value ) {
var __t = {}, name = hierarchy.shift();
if( typeof hierarchy[0] != 'undefined' ) {
__t[name] = build( hierarchy, value );
} else {
__t[name] = value;
}
return __t;
},
merge = function ( list ) {
for (var i = 0; i < list.length; i++) {
obj = jQuery.extend( true, obj, build( list[i].name, list[i].value ) );
};
return obj;
},
extract = function( e ) {
var r = [ '([^\\[]*)' ],
x = [],
co = new RegExp( '\\[', 'g' );
if( typeof h == 'undefined' ){
lvl = e.name.match(co);
if( lvl != null ){
lvl = lvl.length;
} else {
lvl = 0;
}
if( lvl > 1 ) {
for (var i = 0; i < lvl; i++) {
r.push('\\[*([^\\]]*)\\]*');
};
}
var re = new RegExp( r.join(''), 'i' ),
c = e.name.match( re );
c.splice(0, 1);
for (var i = 0; i < c.length; i++) {
x.push(c[i]);
};
return { 'name': x, 'value': e.value };
}
return false;
};
for (var i = 0; i < nameList.length; i++) {
_POST.push( extract( nameList[i] ) );
};
/*
for (var i = 0; i < _POST.length; i++) {
console.group(_POST[i].name);
console.log(_POST[i].name);
console.log(_POST[i].value);
console.groupEnd();
};
*/
return merge( _POST );
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment