0

Here's my nested usage of .each:

itemData["segmentos"] = {};
$("[id^='item-segmentos-']").each(function() {
    $("[id^='item-tipo-']").each(function() {
        itemData["segmentos"][$(outerthis).val()] = $(innerthis).val();
    });
});

How can I use the "outerthis" within the scope of the inner .each?

Ericson Willians
  • 7,606
  • 11
  • 63
  • 114
  • There's an `each`-specific answer which is not covered in the referenced duplicate (and which I think is a better solution for this specific question, as per my answer), hence my vote to reopen as not-an-exact-duplicate – CupawnTae Jan 28 '16 at 23:37

2 Answers2

4

To use the 'outer' this in the inner each() loops, you simply have to cache the 'outer' this in a variable, and then refer to that variable in place of using this within the inner each() loops:

itemData["segmentos"] = {};
$("[id^='item-segmentos-']").each(function() {
    var outerThis = $(this);
    $("[id^='item-tipo-']").each(function() {
        var innerThis = $(this);
        itemData["segmentos"][outerThis.val()] = innerThis.val();
    });
});
David Thomas
  • 249,100
  • 51
  • 377
  • 410
3

You can assign it to a variable in the outer function. This will form a closure and the inner function will have access to the outer variable:

itemData["segmentos"] = {};
$("[id^='item-segmentos-']").each(function() {
    var outerthis = this;
    $("[id^='item-tipo-']").each(function() {
        itemData["segmentos"][$(outerthis).val()] = $(this).val();
    });
});

But note that jQuery passes the index and element as parameters to your callback, which can make for clearer code, e.g.

itemData["segmentos"] = {};
$("[id^='item-segmentos-']").each(function(oIndex, outerElement) {
    $("[id^='item-tipo-']").each(function(iIndex, innerElement) {
        itemData["segmentos"][$(outerElement).val()] = $(innerElement).val();
    });
});
CupawnTae
  • 14,192
  • 3
  • 29
  • 60