0

I have a recursive function that works perfectly fine when outside of angular. It is all native JS but seems to throw errors when trying to use it within angular2/4.

Function:

convertToArray(object, keys) {
    Object.keys(object).forEach(function (k) {
        if (object[k] && typeof object[k] === 'object') {
            this.convertToArray(object[k], keys);
        }
        if (keys.indexOf(k) !== -1 && !Array.isArray(object[k])) {
            object[k] = [object[k]];
        }
    });
}

I invoke the method by:

console.log(this._utils.convertToArray(this.mapRulesData, ['rule']))

When I run it within my project, I am getting the following error:

TypeError: Cannot read property 'convertToArray' of undefined

When I do some console.log within the function, it appears to make it to this line before throwing the error:

this.convertToArray(object[k], keys);

Is there something special with angular when trying to have a method call itself in this manner?

SBB
  • 8,560
  • 30
  • 108
  • 223

1 Answers1

4

this is lost in your function (k) and does not refer to the object itself. Every function creates has it's own this.

Change it to arrow function. Arrow function does not bind its own this.

convertToArray(object, keys) {
    Object.keys(object).forEach(k => {
        if (object[k] && typeof object[k] === 'object') {
            this.convertToArray(object[k], keys);
        }
        if (keys.indexOf(k) !== -1 && !Array.isArray(object[k])) {
            object[k] = [object[k]];
        }
    });
}
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112