7

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
}

2 Answers 2

6

.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;
}
Sign up to request clarification or add additional context in comments.

5 Comments

Curious to know why you're using return(values). It makes it look like a function.
I see. The downside that I see is that type of syntax can confuse beginners. A common point of confusion is typeof x vs typeof(x).
Here's an example. Don't forget who your audience is.
The audience is StackOverflow. I didn't meant to imply that you shouldn't personally use it. I just meant that the () presents an ambiguity for those who don't realize that return is a statement, and never a function, and that after a statement, it's just a plain old group. The typeof question I linked is a good example. Up to you, but I think it would at least help if there was a space when you use it. return (values) Your call. ;)
Note: associative arrays and objects are the same thing in JS.
1
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();

4 Comments

This will create an array of objects. I assume he just wants to get an object.
@FelixKling: I think you're right. I'll update unless someone else beats me to it. ;)
@RightSaidFred: Ya, Felix is right, I want an object, not an array of objects.
excellent, i had to port over an underscore _.map to $.map and for some reason in _.map, wrapping the 'key' and 'value like this: [ question.name, {'value': question.value, 'config': question.config} ] doesn't translate verbatum to $.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.