Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将表单字段转换为JSON对象_Javascript_Jquery_Json_Html - Fatal编程技术网

Javascript 将表单字段转换为JSON对象

Javascript 将表单字段转换为JSON对象,javascript,jquery,json,html,Javascript,Jquery,Json,Html,我有以下表格: <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"/><

我有以下表格:

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

[{"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?

我的变体:

arr=$(“#myForm”).serializeArray();
var res={};
var m,o;
arr.forEach(功能(项目){
m=item.name.match(/[^\]\[]+/g);
o=res;
m、 forEach(函数(v,i,a){
如果(o[v]==未定义){
如果(i+1!==a.长度){
o[v]={};
o=o[v];
返回;
}
o[v]=[项目价值];
}否则{
如果(i+1!==a.长度){
o=o[v];
返回;
}
o[v].推送(item.value);
}
});
})
console.log(res)
$(''+JSON.stringify(res)+'').appendTo('#result')













您可以根据以下内容扩展jQuery并创建类似于中完成的UDF序列化对象:


对不起,我的回答不正确。请看jQurey(“#myForm”)中的第二个答案。serialize()可能与“谢谢你”重复,链接主题中发布的解决方案似乎工作正常。
$.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;
};