How to convert jQuery.serialize() data to JSON object?

后端 未结 12 2116
感情败类
感情败类 2020-12-02 17:11

Is there any better solution to convert a form data that is already serialized by jQuery function serialize(), when the form contains multiple input Array fields. I want to

相关标签:
12条回答
  • 2020-12-02 17:30

    I have recently had this exact problem. Initially, we were using jQuery's serializeArray() method, but that does not include form elements that are disabled. We will often disable form elements that are "sync'd" to other sources on the page, but we still need to include the data in our serialized object. So serializeArray() is out. We used the :input selector to get all input elements (both enabled and disabled) in a given container, and then $.map() to create our object.

    var inputs = $("#container :input");
    var obj = $.map(inputs, function(n, i)
    {
        var o = {};
        o[n.name] = $(n).val();
        return o;
    });
    console.log(obj);
    

    Note that for this to work, each of your inputs will need a name attribute, which will be the name of the property of the resulting object.

    That is actually slightly modified from what we used. We needed to create an object that was structured as a .NET IDictionary, so we used this: (I provide it here in case it's useful)

    var obj = $.map(inputs, function(n, i)
    {
        return { Key: n.name, Value: $(n).val() };
    });
    console.log(obj);
    

    I like both of these solutions, because they are simple uses of the $.map() function, and you have complete control over your selector (so, which elements you end up including in your resulting object). Also, no extra plugin required. Plain old jQuery.

    0 讨论(0)
  • 2020-12-02 17:33

    if you can use ES6, you could do

    const obj = arr.reduce((acc, {name, value}) => ({...acc, [name]: value}), {})
    

    for a serialized array works very well.

    0 讨论(0)
  • 2020-12-02 17:34
    var formdata = $("#myform").serializeArray();
    var data = {};
    $(formdata ).each(function(index, obj){
        data[obj.name] = obj.value;
    });
    

    Simple and fast ;)

    0 讨论(0)
  • 2020-12-02 17:35

    Use the jQuery.serializeJSON plugin. It converts forms using the same format as what you would find in a Rails params object, which is very standard and well tested.

    0 讨论(0)
  • 2020-12-02 17:38
    var formdata = $("#myform").serializeArray();
    
    var data = {};
    
    $(formdata ).each(function(index, obj){
    
             if(data[obj.name] === undefined)
                  data[obj.name] = [];
    
              data[obj.name].push(obj.value);
    
    });
    
    0 讨论(0)
  • 2020-12-02 17:39

    Using the power of reducing function!

    $(form).serializeArray().reduce(function (output, value) {
            output[value.name] = value.value
    
            return output
    }, {})
    
    0 讨论(0)
提交回复
热议问题