2

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?

5
  • 1
    whats the type of input you are using to get the wrong result? Commented Feb 10, 2018 at 17:15
  • Please click <> and create a minimal reproducible example Commented Feb 10, 2018 at 17:15
  • Can you please provide a sample input to this function Commented Feb 10, 2018 at 17:17
  • You have an if followed by an else if...where is the else block. Same goes for inside your else if block, the for-loop has nothing after it. If this is a recursive function, you cannot afford to leave any path way untouched, and this is probably why you are getting undefined at times Commented Feb 10, 2018 at 17:24
  • I guess the problem is your .forEach function. In line 4 you are returning from an anonymous function you are not returning from your actual recursive function. Commented Feb 10, 2018 at 17:34

1 Answer 1

1

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;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Elegant solution. Thank you very much :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.