26

I have the following code:

var selectedTitles = $("#js-otms-titles-table .select_title :checkbox:checked").map(function() {
    return $(this).attr('data-titleId');
});
console.log("Selected titles");
console.log(selectedTitles);

I expect that result will be an array. However I receive object like:

Object["55a930cd27daeaa6108b4f68", "55a930cd27daeaa6108b4f67"]

Is there a special flag to pass to the function? In docs they are talking about arrays as a return value. Did I miss something?

jQuery 1.11.2

3 Answers 3

41

$(selector).map() always returns jQuery object.

To get array from jQuery object use get()

var selectedTitles = $("#js-otms-titles-table .select_title :checkbox:checked").map(function() {
    return $(this).attr('data-titleId');
}).get();
Sign up to request clarification or add additional context in comments.

Comments

9

You need to call .get() on the final result. jQuery's .map() function returns a jQuery object (which can be convenient at times). .get() will fetch the underlying array that it's built on.

See http://api.jquery.com/map/

2 Comments

What is the difference between api.jquery.com/map and api.jquery.com/jquery.map ? I'm a little bit confused.
One works on a jQuery object (generally elements), the other on a plain object or array.
7

The setup:

var a = array(1, 2, 3);
var f = function () { return process_each(this); };
var selector;   // e.g. "div.class" or $("div#id1, div#id2, div#id3")

Ways to map*:

$.map(a, f) - array in - array out

$(selector).map(f) - jQuery object in - jQuery object out

$(selector).map(f).get() - jQuery object in - array out (since jQuery 1.0)

$(selector).map(f).toArray() - jQuery object in - array out (since jQuery 1.4)

*In this context, to map means to process the items in your collection (array or jQuery object), one at a time with your function, and to output a collection (array or jQuery object) of the return values.

Comments

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.