Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery map() returns object instead of array

Tags:

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

like image 719
Tamara Avatar asked Mar 01 '16 20:03

Tamara


People also ask

Does map return an array?

The map() method returns an entirely new array with transformed elements and the same amount of data. In the case of forEach() , even if it returns undefined , it will mutate the original array with the callback .

Does map return an object?

Map object can hold both objects and primitive values as either key or value. When we iterate over the map object it returns the key, value pair in the same order as inserted.

Can I use map on an array of objects?

map() can be used to iterate through objects in an array and, in a similar fashion to traditional arrays, modify the content of each individual object and return a new array. This modification is done based on what is returned in the callback function.

What does map function do in jQuery?

map() method applies a function to each item in an array or object and maps the results into a new array. Prior to jQuery 1.6, $. map() supports traversing arrays only. As of jQuery 1.6 it also traverses objects.


2 Answers

$(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(); 
like image 175
charlietfl Avatar answered Oct 11 '22 19:10

charlietfl


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/

like image 40
Scimonster Avatar answered Oct 11 '22 18:10

Scimonster