DEV Community

Cover image for Iterative nested object traversal
crayoncode
crayoncode

Posted on

2 2

Iterative nested object traversal

Recently I had this problem where I needed to traverse deeply nested objects. More specifically it was about translation files which were of irregular structure (as usual) and partially quite deep (in some spots > 10 levels). So I needed an easy way to traverse through the entire structure and do some transformations / replacements. E.g. convert UPPERCASE to lowercase or replace language-specific quotation marks („“ «», the ones word processors like MS Word write for different languages like German or French) with ASCII quotation marks.

Alt Text

Now, there's the choice of implementing the traversal algorithm recursively or iteratively. Slightly above 10 levels of recursion are unlikely to cause a stack overflow, but I wanted it to be iterative, since in my opinion it's easier to debug.

The key to the iterative implementation is to use a while loop which is kept running as long as the queue of unprocessed objects is not empty. Each object's properties are iterated and if a property contains another object it's simply enqueued to the queue. For any other kind of value a callback is called, where any kind of transformation/replacement can be made.

So, here's the code. If you want to see how it's being written, watch the video. 👋 Any feedback will be appreciated, just let me know and leave a comment. 🙏

Alt Text

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay