ibp73
ibp73

Reputation: 650

Accessing variable inside of forEach callback

I want to access a variable whose purpose is to aggregate records seen so far inside of the callback provided to forEach. Something like this:

var myfn = function() {
    var aggregate_val = [];
    someObj.someFunction(
        arg1,
        arg2,
        (function() {
            ....
            some_array.forEach(function(e) {
                this.aggregate_val.push(e.some_property);
            }, this);
        }).bind(this)
    );
}

Why shouldn't this work?

Upvotes: 2

Views: 5531

Answers (1)

Pavan Ravipati
Pavan Ravipati

Reputation: 1870

You don't need to use this to refer to the array aggregate_val. Try this code:

var myfn = function() {
  var aggregate_val = [];
  some_array.forEach(function(e) {
    aggregate_val.push(e.some_property);
  });
  console.log(some_array) // I added this so you can see the value of some_array
}

Upvotes: 1

Related Questions