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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:13:51  来源:igfitidea点击:

How to get associative array as output from jQuery.map?

javascriptjquery

提问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 selector radioinputs, use this.valueinstead of $(this).val().

如果它们不是selectradio输入,请使用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 nameproperty, you could also use serializeArray.

如果您确实想要一个对象数组,并且如果您的输入具有它们的name属性,您也可以使用serializeArray.

var values = inputs.serializeArray();