如何创建动态命名的JavaScript对象属性? [英] How to create dynamically named JavaScript object properties?
问题描述
这就是我所拥有的
<form>
<input type="text" name="item1" class="grab" value="userInput" />
<input type="text" name="somethingelse1" class="grab" value="differentUserInput" />
... (any number of inputs)
</form>
使用JQuery/Javascript,我要使用名称值对构建对象数组,如下所示:
Using JQuery/Javascript I want to build an array of objects with name value pairs that looks like this:
output = [ {item1: userInput}, {somethingelse1: differentUserInput} ... etc.];
我尝试了这个但没有成功:
I have tried this with no success:
var output = new Array();
$('.grab').each( function(index) {
output.push({$(this).attr('name'): $(this).val()} );
});
我尝试了几种变体,包括尝试使用eval(),但无济于事.如果我删除$(this).attr('name'),并为其指定一个静态名称,那么它可以工作...那么如何创建动态命名的对象?
I have tried several variations including experimenting with eval(), but to no avail. If I remove the $(this).attr('name'), and give it a static name it works... so how can I create dynamically named objects?
推荐答案
文字对象语法不能用于非文字键.
要将非文字键与对象一起使用,需要使用object[keyExpression]
表示法,如下所示. (这相当于object.key
,当keyExpression = "key"
时,但是请注意,前一种情况以表达式作为键,而后一种情况则以标识符为准.)
The literal-object syntax cannot be used for non-literal keys.
To use a non-literal key with an object requires the object[keyExpression]
notation, as below. (This is equivalent to object.key
when keyExpression = "key"
, but note the former case takes an expression as the key and the latter an identifier.)
var output = []
$('.grab').each(function(index) {
var obj = {}
obj[$(this).attr('name')] = $(this).val()
output.push(obj)
})
快乐的编码.
另外,请考虑使用 .map()
:
Also, consider using .map()
:
var output = $('.grab').map(function() {
var obj = {}
obj[$(this).attr('name')] = $(this).val()
return obj
})
这篇关于如何创建动态命名的JavaScript对象属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!