Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm using JQuery map function to get an array of inputs' values:

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

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

{
   id1: value1, 
   id2: value2
}
like image 536
Homam Avatar asked Dec 03 '11 21:12

Homam


2 Answers

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

function getFieldValues() {
    var values = {};
    $("[id^='field']").each(function() {
        values[this.id] = this.value;
    });
    return values;
}
like image 99
jfriend00 Avatar answered Nov 05 '22 18:11

jfriend00


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().

Or if you just wanted an object, use .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.

var values = inputs.serializeArray();
like image 23
RightSaidFred Avatar answered Nov 05 '22 19:11

RightSaidFred