如何将输入名称转换为 JavaScript 数组 [英] How to convert input name to JavaScript array

查看:30
本文介绍了如何将输入名称转换为 JavaScript 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与将 html 输入名称转换为 javascript 对象相关的问题.例如我有一个输入:

<input type="checkbox" name="product[2]">

我有 javascript 代码:

var data = {};$('输入').each(function(){//需要做类似的事情数据[$(this).attr('name')] = $(this).attr('checked');})

我希望得到这样的数据对象;

data = {产品: {1:'检查',2:'检查'}}

这可以不使用正则表达式吗?

解决方案

用字面值替换变量,你会得到:

data["product[1]"] = true;

方括号没有意义,因为它们在字符串中,所以你不会得到任何结果.

有办法解决这个问题.你可以使用 eval: eval("data."+this.name+" = "+(this.checked?"true":"false"));

然而,因为最好避免 eval,试试这个:

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

I have an issue related to converting html inputs names to a javascript object. For example I have an input:

<input type="checkbox" name="product[1]">
<input type="checkbox" name="product[2]">

and I have javascript code:

var data = {};
$('input').each(function(){
    // need to do something like 
    data[$(this).attr('name')] = $(this).attr('checked');
})

I expect to get data object like this;

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

Is this possible without using regular expressions?

解决方案

Replacing your variables with literal values, you get this:

data["product[1]"] = true;

The square brackets have no meaning as they are inside a string, so you won't get any result.

There are ways around this. You could use eval: eval("data."+this.name+" = "+(this.checked?"true":"false"));

However since eval is best avoided, try this:

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

这篇关于如何将输入名称转换为 JavaScript 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆