Reputation: 66560
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?
Upvotes: 2
Views: 985
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();
});
Upvotes: 2
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