Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript serialize form to object

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?

like image 908
Falcon Avatar asked Jun 08 '11 14:06

Falcon


3 Answers

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'
       }
    }
  }
*/
like image 176
Șerban Ghiță Avatar answered Oct 06 '22 01:10

Șerban Ghiță


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;
};
like image 30
Alex Avatar answered Oct 06 '22 00:10

Alex


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.

like image 24
Zach Avatar answered Oct 05 '22 23:10

Zach