0

I need to iterate over a nested function and find the sub-object that has the same key as I want. here is the code:

 const searchObject = (obj, label) => {
        const object = Object.keys(obj).forEach(key => {
            if(label === key) {
                return obj[key];
            } else if(typeof obj[key] === "object") {
                const value = searchObject(obj[key], label);
                if(value) return value;
            }
        });
        return object;
    };

I searched a lot and I found many people are recommending this way but I dont know why I get undefined when I log console.log(searchObject(obj, "Intercept")). (I am using React framework)

3
  • You are returning within .forEach. That won't work. Commented Apr 24, 2020 at 4:01
  • One thing to watch out for is that null also has a type of 'object', so you may need to check for that as well. Commented Apr 24, 2020 at 4:29
  • Why don't you post your data object here, at least a sample? Commented Apr 24, 2020 at 12:13

1 Answer 1

1

forEach returns undefined.

 const searchObject = (obj, label) => {
        var object = {}
        Object.keys(obj).forEach(key => {
            if(label === key) {
                object = obj[key];
            } else if(typeof obj[key] === "object") {
                const value = searchObject(obj[key], label);
                if(value) object = return value;
            }
        });
        return object;
    };
Sign up to request clarification or add additional context in comments.

2 Comments

unfortunately map() did not solve the problem. most of the time it returns arrays of undefined and sometimes it has the object I am looking for. But this should not be the right way.
You probably want Array#find then. Can you post your input and expected output as a minimal reproducible example?

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.