I have form with names 'config[display][x]', 'config[display][y]', 'config[port]',...
, or i can create different format.
and i want to serialize it to JS object like
{config:
display : {x : 'value', y : 'value'},
port : 'value'
}
Somebody know existing solutions to do it?
p.s. i can serialize form with jQuery's .serializeArray(), but i will have array with simple {name : name, value : value} hashes. But how to create object?
See https://github.com/serbanghita/formToObject - there is also a comparison with existing solutions.
var myFormObj = formToObject('myFormId');
/*
console.log(myFormObj);
{
saveSettings: 'Save',
name: 'Serban',
race: 'orc',
settings: {
input: 'keyboard',
video: {
resolution: '1024x768',
vsync: 'on'
}
}
}
*/
I used Ben Almans .serializeObject()
and it worked.
http://benalman.com/projects/jquery-misc-plugins/#serializeobject
The code is small and easy:
$.fn.serializeObject = function(){
var obj = {};
$.each( this.serializeArray(), function(i,o){
var n = o.name,
v = o.value;
obj[n] = obj[n] === undefined ? v
: $.isArray( obj[n] ) ? obj[n].concat( v )
: [ obj[n], v ];
});
return obj;
};
To serialize a JavaScript object to a string, use:
var str = JSON.stringify(obj);
To deserialize a string to a JavaScript object, use:
var obj = JSON.parse(str);
If you are using an older browser that does not support these methods, you can use the JSON2 library from Douglas Crockford.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With