Skip to content Skip to sidebar Skip to footer

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 {

Solution 1:

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

Solution 2:

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() {
    varself = $(this);
    return {
      big: self.hasClass('big') || self.hasClass('medium'),
      offset: self.offset(),
      width: self.width(),
      height: self.height()
    };
  }).get(); 

});

Here's a fiddle

Post a Comment for "Map Map Return Flat Array In Jquery"