Today at work I was tasked with iterating over a JavaScript (TypeScript) object to find a particular property or key nested somewhere within the object. The tricky part is the object can have infinite nesting, so we don’t know how deep we need to dig to find the needle in the haystack.
I thought someone else may end up needing a solution to this problem, so I decided to write this blog post. I found a StackOverflow article which was pretty helpful, however the author of the answer to that question only posted partial bits of the solution, and didn’t post a complete function.
After a little work on replit.com, I came up with a function that does the job for me. For my use case, I only needed to find one needle in the haystack. If you need to find multiple instances of the same property or key, then you’ll need to re-work my function.
Hope you find this function helpful internet friend!