DEV Community

Cover image for Iterative nested object traversal
crayoncode
crayoncode

Posted on

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

Top comments (0)