Simple idea: just have a plugin (more a basic function). That I can use with jQuery in different ways it offers, means:
var myNewVar = $.myNewFunction( myVar );
var myNewVar = $().myNewFunction( myVar );
I want to know if what I did is the good way to doesn't repeat the code, or if their is a better way to.
Here my plugin:
// New function to jquery to change an array (from form) to an object
$.formArrayToObject = function( array ) {
var form = {};
$(array).each(function(){
if( !form[this.name] ) {
form[this.name] = this.value;
}
else {
if ( !Array.isArray(form[this.name]) ) {
form[this.name] = [form[this.name]];
}
form[this.name].push(this.value);
}
});
return form;
};
// Second declaration to be able to call both $. and $().
jQuery.fn.formArrayToObject = function() {
$.formArrayToObject();
};