Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/87.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数组_Javascript_Html - Fatal编程技术网

如何将输入名称转换为JavaScript数组

如何将输入名称转换为JavaScript数组,javascript,html,Javascript,Html,我有一个关于将html输入名称转换为javascript对象的问题。 例如,我有一个输入: <input type="checkbox" name="product[1]"> <input type="checkbox" name="product[2]"> 我希望得到这样的数据对象 data = { product: { 1: 'checked', 2: 'checked' } } 在不使用正则表达式的情况下,这是可能

我有一个关于将html输入名称转换为javascript对象的问题。 例如,我有一个输入:

<input type="checkbox" name="product[1]">
<input type="checkbox" name="product[2]">
我希望得到这样的数据对象

data = {
    product: {
        1: 'checked',
        2: 'checked'
    }
}

在不使用正则表达式的情况下,这是可能的吗?

将变量替换为文本值,可以得到以下结果:

data["product[1]"] = true;
方括号没有任何意义,因为它们位于字符串中,所以不会得到任何结果

这是有办法的。您可以使用eval:
eval(“数据”+this.name+“=”+(this.checked?:“false”)

但是,由于最好避免使用
eval
,请尝试以下方法:

var m = this.name.match(/(.*)\[(\d+)\]/);
data[m[0]][m[1]] = this.checked;

是的,一般来说这是可能的。您可以执行以下操作:

var noregexp = $(this).attr('name').split("[");
if (noregexp.length==2) {
    //should be
    var the_name = noregexp[0];
    var the_index = noregexp[1].substr(0,noregexp[1].length-1); //this will get the index with removed ]
}

这是我自己想出来的。这不是一个漂亮的解决方案,而是一个没有regexp的解决方案。您可以使用以下方法获得所需的数据结构:

var data = {product: []};
$('input').each(function(){
    data.product[$(this).attr('name').match(/product\[([\d]*)\]/)[1]] = $(this).prop('checked');
})
console.log(data);

勾选thid

很难从示例中看出您想要什么。在那个例子中,输入的名称是什么?他想要一个两级的结果,正如
name
的值所暗示的那样。Frits van Campen是对的。我需要两层深的阵列/object@FritsvanCampen该问题是在该评论之后编辑的:)您可以使用不同的输入名称吗?eval(“数据”+此.name+“=”+(此.checked?:“真”);-伟大的谢谢我尝试了eval(this.name),但得到了“未定义的变量乘积…”。太谢谢你了!
var data = {product: []};
$('input').each(function(){
    data.product[$(this).attr('name').match(/product\[([\d]*)\]/)[1]] = $(this).prop('checked');
})
console.log(data);