Javascript serializes the form for an object

I have a form with names 'config[display][x]', 'config[display][y]', 'config[port]',..., or I can create another format. and I want to serialize it to a JS object like

{config:
    display : {x : 'value', y : 'value'},
    port : 'value'
}

Does anyone know of existing solutions for this?

ps I can serialize the form using jQuery.serializeArray (), but I will have an array with simple hashes {name: name, value: value}. But how to create an object?

+3
source share
5 answers

Check out JSON Serialization in jQuery for a comprehensive discussion on serialization

-5
source

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'
       }
    }
  }
*/
+3

Ben Almans .serializeObject(), .

http://benalman.com/projects/jquery-misc-plugins/#serializeobject

The code is small and simple:

$.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;
};
+2
source

To serialize a JavaScript object into a string, use:

var str = JSON.stringify(obj);

To deserialize a string for 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.

0
source

I believe this is what you are looking for:

function assignByPath(obj,path,value){
    if (path.length == 1) {
        obj[path[0]] = value;
        return obj;
    } else if (obj[path[0]] === undefined) {
        obj[path[0]] = {};
    } 
    return assignByPath(obj[path.shift()],path,value);
}

$.fn.serializeObject = function(){
    var obj = {};

    $.each( this.serializeArray(), function(i,o){
        var n = o.name,
        v = o.value;
        path = n.replace('[','.').replace('][','.').replace(']','').split('.');

        assignByPath(obj,path,v);
    });

    return obj;
};
0
source

All Articles