How to serialize a form into an object (with tree structure)?

前端 未结 2 805
南方客
南方客 2021-01-06 17:00

I have a form

2条回答
  •  天涯浪人
    2021-01-06 17:42

    Add this method to help you build the tree

    // add keys to an object as a tree
    // ["a", "b", "c"] will generate
    // a { b: { c: def } }
    // def is the value of the leaf node
    var AddToTree = function(obj, keys, def)
    {
        for (var i = 0, length = keys.length; i < length; ++i)
            obj = obj[keys[i]] = i == length - 1 ? def : obj[keys[i]] || {};
    };
    

    Create a function for a jQuery selector that will convert the form in an object

    $.fn.serializeObject = function()
    {
       var o = {}; // final object
       var a = this.serializeArray(); // retrieves an array of all form values as
                                      // objects { name: "", value: "" }
    
       $.each(a, function() {
           var ns = this.name.split("."); // split name to get namespace
           AddToTree(o, ns, this.value); // creates a tree structure
                                         // with values in the namespace
       });
    
       return o;
    };
    

    With these two functions define you can set an event on the submit button:

    $(":submit").click(function(e){
        // contains the object from the form
        // respecting element namespaces
        var obj = $("form").serializeObject();
    });
    

提交回复
热议问题