Reputation: 52501
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.
Upvotes: 1
Views: 1163
Reputation: 413712
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.
Upvotes: 2