1

I have an array inside an $.each function. I want to iterate through it to create a new or modified array. But I need to access the $(this) from the outside $.each loop:

// target these data attributes:
$selector = $('[data-my0], [data-my1], [data-my2]');

$.each($selector, function() {        

    var $this = $(this), // cache selector
        keys = ['my0', 'my1', 'my2']; // array of data keys

    // I want to use the keys array to make a vals array to this:
    // var vals = [$this.data('my0'), $this.data('my1'), $this.data('my2')];

    // This doesn't seem to work (can't read from length 0 error):
    var vals = $.map( keys, function( key ) { return $this.data(key); });

}); 

I think it's possible to do this using using $.each or $.map but this is where I'm stuck. I know $(this) not used normally with $.map like it is with $.each. In this case, I'm trying to pass the $this from the outside that represents the selector.

4
  • 1
    Not part of the problem, but you can write $selector.each(...) too. Commented Sep 16, 2011 at 12:55
  • You have a type with ); I think. Commented Sep 16, 2011 at 13:08
  • 1
    @pimvdb yes that was a problem too but it wouldn't cause that "can't read from length 0" error. I don't get that error in the jsfiddle I did from the code. Commented Sep 16, 2011 at 13:16
  • @pimvdb Thanks (that's what happens when I have to wake up at 5:30 and drive my mom to the airport LOL). Commented Sep 16, 2011 at 14:58

1 Answer 1

2

Wait - you're passing "vals" into your "$.map()" cal instead of "keys":

var vals = $.map( keys, function( key ) { return $this.data(key); });

Here is a jsfiddle. The code works just fine, though without seeing your actual HTML it's hard to know exactly what you expect to happen.

Sign up to request clarification or add additional context in comments.

2 Comments

That's good and bad b/c it means this works but I must have a problem elsewhere. Thank you :)
and the html is like <div data-my0='hello' data-my1='out' data-my2='there'></div> - worked that way too in the fiddle. Thx again.

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.