<\/script>')

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

I use the jQuery map function to get an array of input values:

var inputs = $("[id^='field']");
var values = inputs.map(function () { 
                             return $(this).val(); 
                        }).get();

I would like to get an associative array from [id, value]:

{
   id1: value1, 
   id2: value2
}
+5
source share
2 answers

.map() returns an array, so if you want the object to have id values ​​as keys, you can do it like this:

function getFieldValues() {
    var values = {};
    $("[id^='field']").each(function() {
        values[this.id] = this.value;
    });
    return(values);
}
+5
source
var values = inputs.map(function () { 
                             var obj = {};
                             obj[ this.id ] = $(this).val(); 
                             return obj;
                        }).get();

If they are not inputs selector radio, use this.valueinstead $(this).val().

Or, if you just want an object, use .each.

var obj = {};
inputs.each(function () { 
                             obj[ this.id ] = $(this).val(); 
                        });

, name, serializeArray.

var values = inputs.serializeArray();
+1

All Articles