如何将表单数据序列化为具有嵌套属性的对象

How to serialize form data into an object with nested properties

本文关键字:嵌套 属性 对象 表单 数据 序列化      更新时间:2023-09-26

给定以下输入:

<input name="person[1]['first']" />
<input name="person[2]['first']" />
<input name="person[3]['first']" />

我想将其序列化为一个对象,如下所示:

person = {
  1: {first:value},
  2: {first:value},
  3: {first:value}
}

这个功能现在在jQuery或javascript中可用吗?还是我必须写一个函数才能做到这一点?

当它在<form>标签内时,您可以使用:

$(formElement).serialize();

您正在寻找serializeArray()

编辑

在表单提交中添加简短示例:

$('#container').on('submit', '#myForm', function(e) {
    e.preventDefault();
    var data = $(this).serializeArray(); // $(this) contains the form element
    console.log(data); // will output serialized data
    console.log(data.email); // will output email input value (if any)
});