2

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

3
  • Interesting...seems like it should work. Could you make a fiddle (swap images out for something else)? Commented Oct 3, 2013 at 13:22
  • try to switch the order of the call of your functions, first img.map then .post-entry.map ... Commented Oct 3, 2013 at 13:28
  • @Oliboy50 I can't because .post-entry is a parent. Commented Oct 3, 2013 at 13:30

2 Answers 2

6

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();
Sign up to request clarification or add additional context in comments.

Comments

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

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.