Reputation: 183
I have recursive function which looks thru deeply nested object or array of ojbects and finds wanted object by key. Problem is when i want to return result object i get undefined and i dont know why. When i console log result i get correct result.
function checkForDependency(name, scope) {
if (Array.isArray(scope)) {
scope.forEach((el) => {
return checkForDependency(name, el)
})
} else if (typeof scope === 'object') {
if (scope.hasOwnProperty('name') && scope.name == name && scope.hasOwnProperty('dependency')) {
console.log('dependency:', scope.dependency)
return {
type: scope.dependency
}
} else {
for (let key in scope) {
if (Array.isArray(scope[key]) || typeof scope[key] === 'object') {
return checkForDependency(name, scope[key])
}
}
}
}
}
Could you help me please?
Upvotes: 2
Views: 129
Reputation: 386550
You could use a temporary variable with early exit an a check if the temporary variable has a value, then exit the function.
You need not to check for array, because you could iterate the keys of the array or as an object, which is the same.
function checkForDependency(name, scope) {
var temp;
if (typeof scope !== 'object') { // early exit if no object
return;
}
if (scope.name === name && 'dependency' in scope) { // check value and key
console.log('dependency:', scope.dependency)
return { type: scope.dependency }; // return found value
}
if (Object.keys(scope).some(key => temp = checkForDependency(name, scope[key]))) {
return temp;
}
}
Upvotes: 1