Home >Web Front-end >JS Tutorial >jQuery serializeObject based on serializeArray

jQuery serializeObject based on serializeArray

巴扎黑
巴扎黑Original
2017-07-03 13:56:231637browse

jQueryThere is a method $.fn.serialize, which can serialize the form into a string; there is a method $.fn.serializeArray, which can serialize the form into an array.
If you need to serialize it into a JSON object, you can easily implement it by writing the method serializeObject based on serializeArray:

//work with jQuery 1.x
jQuery.prototype.serializeObject=function(){
	var obj=new Object();
	$.each(this.serializeArray(),function(index,param){
		if(!(param.name in obj)){
			obj[param.name]=param.value;
		}
	});
	return obj;
};


Note: When parameters with the same name appear in the form, serializeObject will take the first one and ignore the subsequent ones.

If

<form>
	<input type="text" name="username" />
	<input type="text" name="password" />
</form>

then

jQuery("form").serialize(); //"username=&password="
jQuery("form").serializeArray(); //[{name:"username",value:""},{name:"password",value:""}]
jQuery("form").serializeObject(); //{username:"",password:""}



20150125Update
==== =======
+ This version is no longer compatible with IE8
+ Fixed a logic error

//work with jQuery 2.x
jQuery.prototype.serializeObject=function(){
	var hasOwnProperty=Object.prototype.hasOwnProperty;
	return this.serializeArray().reduce(function(data,pair){
		if(!hasOwnProperty.call(data,pair.name)){
			data[pair.name]=pair.value;
		}
		return data;
	},{});
};



20150705 update
===========

+ Reduce method dependencies and expand the scope of compatibility
+ Switch to native loops to improve code performance

//work with jQuery Compact 3.x
jQuery.prototype.serializeObject=function(){
	var a,o,h,i,e;
	a=this.serializeArray();
	o={};
	h=o.hasOwnProperty;
	for(i=0;i<a.length;i++){
		e=a[i];
		if(!h.call(o,e.name)){
			o[e.name]=e.value;
		}
	}
	return o;
};

The above is the detailed content of jQuery serializeObject based on serializeArray. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn