如何创建动态命名的 JavaScript 对象属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8084003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create dynamically named JavaScript object properties?
提问by user988300
Here is what I have
这是我所拥有的
<form>
<input type="text" name="item1" class="grab" value="userInput" />
<input type="text" name="somethingelse1" class="grab" value="differentUserInput" />
... (any number of inputs)
</form>
Using JQuery/Javascript I want to build an array of objects with name value pairs that looks like this:
使用 JQuery/Javascript 我想构建一个具有名称值对的对象数组,如下所示:
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()} );
});
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?
我尝试了几种变体,包括尝试使用 eval(),但都无济于事。如果我删除 $(this).attr('name'),并给它一个静态名称,它就可以工作......那么我如何创建动态命名的对象?
回答by
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 expressionas the key and the latter an identifier.)
文字对象语法不能用于非文字键。要对对象使用非文字键需要object[keyExpression]
符号,如下所示。(这相当于object.key
when keyExpression = "key"
,但请注意,前一种情况将表达式作为键,而后一种情况则是标识符。)
var output = []
$('.grab').each(function(index) {
var obj = {}
obj[$(this).attr('name')] = $(this).val()
output.push(obj)
})
Happy coding.
快乐编码。
Also, consider using .map()
:
另外,请考虑使用.map()
:
var output = $('.grab').map(function() {
var obj = {}
obj[$(this).attr('name')] = $(this).val()
return obj
})
回答by Francisco Paz
I took only the id of the form as a parameter of this function:
我只将表单的 id 作为这个函数的参数:
function form2JSON(form){
var info_ser = $('#'+form).serialize();
var data = info_ser.split('&');
var output = {};
$.each( data, function( i, l ){
var data_input = l.split('=');
output[data_input[0]] = data_input[1];
});
return output;
}
The result object is something like this Object { fieldname="value", fieldname1="value1", fieldname2="value3", ...}
结果对象是这样的 Object { fieldname="value", fieldname1="value1", fieldname2="value3", ...}