jQuery serializeArray()键值对

Aks*_*hat 38 jquery serialization

我在序列化表单时遇到了一些麻烦

<form>
    <input type="text" name="name1" value="value1"/>
    <input type="text" name="name2" value="value2"/>
</form>

$(form).serializeArray()
Run Code Online (Sandbox Code Playgroud)

将返回[{name:"name1",value:"value1"},{name:"name2",value:"value2"}]对.

是否有可能在表单中获得输出

{name1:value1,name2:value2}
Run Code Online (Sandbox Code Playgroud)

这样他们更容易处理?

Dar*_*rov 70

var result = { };
$.each($('form').serializeArray(), function() {
    result[this.name] = this.value;
});

// at this stage the result object will look as expected so you could use it
alert('name1 = ' + result.name1 + ', name2 = ' + result.name2);
Run Code Online (Sandbox Code Playgroud)

现场演示.

  • 如果您有一个带有复选框或单选按钮的表单,则此方法将不起作用,因为它们都具有相同的名称属性.有关处理的任何想法(除了一堆条件和手动创建数组)? (9认同)

小智 38

$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }      
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};
Run Code Online (Sandbox Code Playgroud)


Hol*_*ter 24

如果您的表单没有复选框或单选按钮,则接受的答案很有效.由于这些组的所有组都具有相同的name属性,因此您需要在对象内创建一个数组值.所以对于html来说:

<input type="checkbox" value="1" name="the-checkbox">
<input type="checkbox" value="1" name="the-checkbox">
<input type="checkbox" value="1" name="the-checkbox">
Run Code Online (Sandbox Code Playgroud)

你会得到:

{the-checkbox:['1', '2', '3']}
Run Code Online (Sandbox Code Playgroud)

这段代码很好地处理了一切.

/*!
 * jQuery serializeObject - v0.2 - 1/20/2010
 * http://benalman.com/projects/jquery-misc-plugins/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */

// Whereas .serializeArray() serializes a form into an array, .serializeObject()
// serializes a form into an (arguably more useful) object.

(function($,undefined){
  '$:nomunge'; // Used by YUI compressor.

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

})(jQuery);
Run Code Online (Sandbox Code Playgroud)

用法

$(form).serializeObject();
Run Code Online (Sandbox Code Playgroud)


Ere*_*bih 5

new_obj = {}

$.each($(form).serializeArray(), function(i, obj) { new_obj[obj.name] = obj.value })
Run Code Online (Sandbox Code Playgroud)

您的数据在new_obj中


Nic*_*ons 5

您可以非常简单地使用.reduce()和解构赋值来完成此操作:

const arr = $('form').serializeArray(); // get the array
const data = arr.reduce((acc, {name, value}) => ({...acc, [name]: value}),{}); // form the object
Run Code Online (Sandbox Code Playgroud)

例子:

const arr = $('form').serializeArray(); // get the array
const data = arr.reduce((acc, {name, value}) => ({...acc, [name]: value}),{}); // form the object
Run Code Online (Sandbox Code Playgroud)
$('form').on('submit', function(e) {
  e.preventDefault(); // only used for example (so you can see output in console);
  const arr = $(this).serializeArray(); // get the array
  const data = arr.reduce((acc, {name, value}) => ({...acc, [name]: value}),{}); // form the object
  console.log(data);
});
Run Code Online (Sandbox Code Playgroud)

或者如果你能支持的话,Object.fromEntries()甚至更容易:.map()

例子:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <input type="text" placeholder="username" name="username"/>
  <input type="email" placeholder="email" name="email"/>
  <input type="submit" />
</form>
Run Code Online (Sandbox Code Playgroud)
$('form').on('submit', function(e) {
  e.preventDefault(); // only used for example (so you can see output in console);
  const arr = $(this).serializeArray(); // get the array
  const data = Object.fromEntries(arr.map(({name, value}) => [name, value]));
  console.log(data);
});
Run Code Online (Sandbox Code Playgroud)