javascript 如何从 jQuery.map 获取关联数组作为输出?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8371117/
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 get associative array as output from jQuery.map?
提问by Homam
I'm using JQuery mapfunction to get an array of inputs' values:
我正在使用 JQuery映射函数来获取输入值数组:
var inputs = $("[id^='field']");
var values = inputs.map(function () {
return $(this).val();
}).get();
I would like to get an associative array of [id, value]:
我想得到一个 [id, value] 的关联数组:
{
id1: value1,
id2: value2
}
回答by jfriend00
.map()
returns an array, so if you want an object with id values as the keys, then you can do it like this:
.map()
返回一个数组,所以如果你想要一个以 id 值作为键的对象,那么你可以这样做:
function getFieldValues() {
var values = {};
$("[id^='field']").each(function() {
values[this.id] = this.value;
});
return values;
}
回答by RightSaidFred
var values = inputs.map(function () {
var obj = {};
obj[ this.id ] = $(this).val();
return obj;
}).get();
If they're not select
or radio
inputs, use this.value
instead of $(this).val()
.
如果它们不是select
或radio
输入,请使用this.value
代替$(this).val()
。
Or if you just wanted an object, use .each
.
或者,如果您只想要一个对象,请使用.each
.
var obj = {};
inputs.each(function () {
obj[ this.id ] = $(this).val();
});
If you did want an array of objects, and if your inputs have their name
property, you could also use serializeArray
.
如果您确实想要一个对象数组,并且如果您的输入具有它们的name
属性,您也可以使用serializeArray
.
var values = inputs.serializeArray();