Skip to content Skip to sidebar Skip to footer

Convert Form Fields Into Json Object

I have the following form:
); } else { o[this.name] = this.value || ''; } }); return o; };

Solution 2:

My variant:

arr = $("#myForm").serializeArray();

var res={};
var m,o;
arr.forEach(function(item){
	m = item.name.match(/[^\]\[]+/g);
	o = res;
	m.forEach(function(v,i,a){
		if(o[v] === undefined) {
			if(i+1 !== a.length) {
				o[v] = {};
				o = o[v];
				return;
			}
			o[v] = [item.value];
		} else {
			if(i+1 !== a.length) {
				o = o[v];
				return;
			}
			o[v].push(item.value);
		}
	});
})

console.log(res)
$('<pre>'+JSON.stringify(res)+'</pre>').appendTo('#result')
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><body><formid="myForm"method="POST"><inputtype="text"name="matrix[]"value="1"/><br/><inputtype="text"name="matrix[]"value="2"/><br/><inputtype="text"name="matrix[]"value="3"/><br/><inputtype="text"name="multi_matrix[colors][]"value="red"/><br/><inputtype="text"name="multi_matrix[colors][]"value="blue"/><br/><inputtype="text"name="multi_matrix[weight][]"value="75"/><br/><inputtype="text"name="multi_matrix[weight][]"value="83"/><br/><inputtype="text"name="multi_matrix[weight_real][]"value="83.32"/><br/><inputtype="text"name="multi_matrix[weight_real][]"value="83.65"/><br/><inputtype="text"name="multi_matrix[price][unreal][]"value="383.32"/><br/><inputtype="text"name="multi_matrix[price][unreal][]"value="183.65"/><br/><inputtype="submit"value="Send"></form><divid="result"></div>
{"matrix":["1","2","3"],"multi_matrix":{"colors":["red","blue"],"weight":["75","83"],"weight_real":["83.32","83.65"],"price":{"unreal":["383.32","183.65"]}}}

Post a Comment for "Convert Form Fields Into Json Object"