How to Traverse an Object of Arbitrary Depth in JavaScript
Tags: javascript, node, webdev, programming
Published: 2020-10-29 12:32:56

---
title: How to Traverse an Object of Arbitrary Depth in JavaScript
published: true
description: Sometimes we find that we need to traverse an object and perform some operation on it at some arbitrary depth. While this seems like a tough challenge, we can make use of recursion, mutability, and object references to get the job done in short order.
tags: javascript, node, webdev, programming
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/q3bnfrm4253xm6wtuac4.jpg
canonical_url: https://typeofnan.dev/how-to-traverse-an-object-of-arbitrary-depth-in-javascript/
---

Sometimes we find that we need to traverse an object and perform some operation on it at some arbitrary depth. While this seems like a tough challenge, we can make use of _recursion_, _mutability_, and _object references_ to get the job done in short order.

<hr />

### If you enjoy this tutorial, please give it a 💓, 🦄, or 🔖 and consider:

📬 signing up for [my free weekly dev newsletter](https://buttondown.email/devtuts)
🎥 subscribing to [my free YouTube dev channel](https://www.youtube.com/c/devtutsco?sub_confirmation=1)

<hr />

# Our Example Challenge: Deep Word Replacement

Let's say we have an object that all the text fields of a dog adoption application our user has provided us. However, the user entered `[tbd]` in the places where the dog's name should be&mdash;picking a dog's name is hard. Alas, our user has finally selected the name `Daffodil` for his puppy, and we must now replace all the `[tbd]` strings in our object.

Unfortunately, our object is complex and of arbitrary depth. We must make this string replacement anywhere in our object!

Here's our object:

```javascript
const application = {
  section1: {
    question1: {
      text: "What will your pet's name be?",
      response: '[tbd]',
    },
    question2: {
      text: 'What will the names of all the pets in your house be?',
      response: ['Fred', 'Whiskers', '[tbd]'],
      subquestion2: {
        text: 'How will you take care of your new pet?',
        response: 'I will feed [tbd] three times a day and pat her head.',
      },
    },
  },
};
```

Let's think about this problem in steps before we write our solution. Here's what we need to do:

- Create a function that takes an object as an argument.
- For each key in that object, if that key is a `string`, do our word replace. (mutation!)
- If the key is an `object`, send that key back through the initial function (recursion!)

We can see how this looks in JavaScript:

```javascript
function replaceTbd(obj) {
  for (let key in obj) {
    if (typeof obj[key] === 'string') {
      obj[key] = obj[key].replace('[tbd]', 'Daffodil');
    }
    if (typeof obj[key] === 'object') {
      replaceTbd(obj[key]);
    }
  }
}
```

Kind of simple actually! Let's see if that works on our object.

```javascript
replaceTbd(application);

console.log(application);
/*
{
  section1: {
    question1: {
      text: "What will your pet's name be?",
      response: 'Daffodil',
    },
    question2: {
      text: 'What will the names of all the pets in your house be?',
      response: ['Fred', 'Whiskers', 'Daffodil'],
      subquestion2: {
        text: 'How will you take care of your new pet?',
        response: 'I will feed Daffodil three times a day and pat her head.',
      },
    },
  },
};
*/
```

Success! Do note that we didn't return anthing from our `replaceTbd` function&mdash;it's mutating our input object as it dives down the tree! If this isn't desired behavior, you could consider looking into a deep clone library to first clone your object and then mutate the clone.

# Conclusion

Working with deep objects can be intimidating, but it gets much easier when you master the concepts of _recursion_, _mutability_, and _object references_.

<hr />

### If you enjoy this tutorial, please give it a 💓, 🦄, or 🔖 and consider:

📬 signing up for [my free weekly dev newsletter](https://buttondown.email/devtuts)
🎥 subscribing to [my free YouTube dev channel](https://www.youtube.com/c/devtutsco?sub_confirmation=1)