gpt4 book ai didi

javascript - 将表单字段转换为 JSON 对象

转载 作者:行者123 更新时间:2023-11-28 00:11:33 26 4
gpt4 key购买 nike

我有以下表格:

<form id="myForm" method="POST">        
<input type="text" name="matrix[]" value="1"/><br/>
<input type="text" name="matrix[]" value="2"/><br/>
<input type="text" name="matrix[]" value="3"/><br/>
<input type="text" name="multi_matrix[colors][]" value="red"/><br/>
<input type="text" name="multi_matrix[colors][]" value="blue"/><br/>
<input type="text" name="multi_matrix[weight][]" value="75"/><br/>
<input type="text" name="multi_matrix[weight][]" value="83"/><br/>
<input type="submit" value="Send">
</form>

现在我想使用 JavaScript/jQuery 将这些值转换为 JSON 字符串。当我使用 JSON.stringify($("#myForm").serializeArray()) 代码时,它返回以下内容:

[{"name":"matrix[]","value":"1"},{"name":"matrix[]","value":"2"},{"name":"matrix[]","value":"3"},{"name":"multi_matrix[colors][]","value":"red"},{"name":"multi_matrix[colors][]","value":"blue"},{"name":"multi_matrix[weight][]","value":"75"},{"name":"multi_matrix[weight][]","value":"83"}]

正如您所看到的,所有字段都有一个单独的条目,但我想将它们连接在一起以获得以下内容:

{"matrix":[1,2,3],"multi_matrix":{"colors":["red","blue"],"weight":[75,83]}}

有没有内置函数可以做到这一点?或者我是否必须迭代所有字段并自己手动创建 JSON?

最佳答案

您可以扩展 jQuery 并创建 UDF serializeObject,就像 this answer 中所做的那样,基于serializeArray() :

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

关于javascript - 将表单字段转换为 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30832425/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com