如何将表单的所有元素转换为JavaScript对象?

我希望有某种方法从表单自动构建JavaScript对象,而不必遍历每个元素。我不希望使用$('#formid').serialize();返回的字符串;,我也不希望$('#formid').serializeArray()返回映射;


当前回答

const formData = new FormData(form);

let formDataJSON = {};

for (const [key, value] of formData.entries()) {

    formDataJSON[key] = value;
}

其他回答

对于这个问题,我找到的最简单、最准确的方法是使用bbq插件或这个插件(大约0.5K字节大小)。

它也适用于多维阵列。

$.fn.serializeObject=函数(){return$.departam(this.serialize());};

对于语义ui/formantic ui,有一个内置的行为get值:

const fields = $("#myForm.ui.form").form('get values');
const jsonStr = JSON.stringify(fields);

看见https://fomantic-ui.com/behaviors/form.html#/settings

get-values(标识符)返回与标识符数组匹配的元素值的对象。如果未通过IDS,将返回所有字段

有什么问题:

var data = {};
$(".form-selector").serializeArray().map(function(x){data[x.name] = x.value;}); 

这是一个使用reduce的单行。Reduce是一个函数函数,它获取传递函数的返回值,并在下一次迭代中将其与列表中的第n个值一起传递回传递函数。

$('#formid').serializeArray().reduce((o,p) => ({...o, [p.name]: p.value}))

我们必须使用一些技巧来实现这一点:

…o(扩展语法)插入o中的所有键:值对包装我们在()中返回的对象,以将其与表示函数的{}区分开来将密钥(p.name)换行为[]

这是对Tobias Cohen函数的改进,该函数在多维数组中运行良好:

http://jsfiddle.net/BNnwF/2/

然而,这不是一个jQuery插件,但如果您想这样使用它,只需几秒钟就可以将它变成一个:只需替换函数声明包装器:

function serializeFormObject(form)
{
    ...
}

具有:

$.fn.serializeFormObject = function()
{
    var form = this;
    ...
};

我想这与梅斯克的解决方案相似,因为它做了相同的事情,但我认为这有点干净和简单。我还将macek的测试用例输入添加到小提琴中,并添加了一些额外的输入。到目前为止,这对我来说很好。

function serializeFormObject(form)
{
    function trim(str)
    {
        return str.replace(/^\s+|\s+$/g,"");
    }

    var o = {};
    var a = $(form).serializeArray();
    $.each(a, function() {
        var nameParts = this.name.split('[');
        if (nameParts.length == 1) {
            // New value is not an array - so we simply add the new
            // value to the result object
            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 || '';
            }
        }
        else {
            // New value is an array - we need to merge it into the
            // existing result object
            $.each(nameParts, function (index) {
                nameParts[index] = this.replace(/\]$/, '');
            });

            // This $.each merges the new value in, part by part
            var arrItem = this;
            var temp = o;
            $.each(nameParts, function (index) {
                var next;
                var nextNamePart;
                if (index >= nameParts.length - 1)
                    next = arrItem.value || '';
                else {
                    nextNamePart = nameParts[index + 1];
                    if (trim(this) != '' && temp[this] !== undefined)
                        next = temp[this];
                    else {
                        if (trim(nextNamePart) == '')
                            next = [];
                        else
                            next = {};
                    }
                }

                if (trim(this) == '') {
                    temp.push(next);
                } else
                    temp[this] = next;

                temp = next;
            });
        }
    });
    return o;
}