jcubic
jcubic

Reputation: 66560

map map return flat array in jQuery

I want to have array of arrays.

My code:

image_data = $('.post-entry').map(function() {
    return $(this).find('img').map(function() {
      var self = $(this);
      return {
        big: self.hasClass('big') || self.hasClass('medium'),
        offset: self.offset(),
        width: self.width(),
        height: self.height()
      };
    }).get();
  }).get();

but when I have two post-entry elements and each have 4 images I have array of 8 images. How can I get array of two elements of 4 elements each? Why I got flat array?

JSFIDDLE

Upvotes: 2

Views: 985

Answers (2)

billyonecan
billyonecan

Reputation: 20260

You could create an empty array, and then add an index for each post-entry, containing the img objects. I suspect there could be a better way to do this, though:

var image_data = [];
$('.post-entry').each(function(i) {

  image_data[i] = $(this).find('img').map(function() {
    var self = $(this);
    return {
      big: self.hasClass('big') || self.hasClass('medium'),
      offset: self.offset(),
      width: self.width(),
      height: self.height()
    };
  }).get(); 

});

Here's a fiddle

Upvotes: 2

Frédéric Hamidi
Frédéric Hamidi

Reputation: 262979

That's because the documentation for map() says (emphasis mine):

The function can return an individual data item or an array of data items to be inserted into the resulting set. If an array is returned, the elements inside the array are inserted into the set.

Therefore, map() flattens the arrays you return, and this behavior is by design.

Try wrapping these arrays into another array, as I believe map() only flattens once:

image_data = $('.post-entry').map(function() {
    return [
        $(this).find('img').map(function() {
            var self = $(this);
            return {
                big: self.hasClass('big') || self.hasClass('medium'),
                offset: self.offset(),
                width: self.width(),
                height: self.height()
            };
        }).get()
    ];
}).get();

Upvotes: 6

Related Questions