The problem is that your this is different from the function you passed to forEach . You need to bind the external this to the internal function:
getParentFolder: function(searchroot, childFolder) { searchroot.subfolders.forEach(function(folder) { if (folder.key == childFolder.key) { return searchroot; } else { if (folder.subfolders) { return this.getParentFolder(folder, childFolder); } } }, this);
From Array.prototype.forEach() to MDN:
Syntax:
arr.forEach(function callback(currentValue, index, array) {
Alternative solution using ES6:
Like mishu mentioned in the comments, the new ES6 arrow syntax also solves this problem. Your code in ES6 will look something like this:
getParentFolder: function(searchroot, childFolder) { searchroot.subfolders.forEach((folder) => { if (folder.key == childFolder.key) { return searchroot; } else { if (folder.subfolders) { return this.getParentFolder(folder, childFolder); } } }); }
The ES6 arrow functions do not bind this (see MDN ), so the external this can be obtained from inside the arrow function.
Please note that not all browsers support arrow functions (see Browser Compatibility in MDN ). To support older browsers, you can redirect ES6 to ES5 using Babel .
source share