How to get all keys of a deep object in JavaScript?

Sometimes, we want to get all keys of a deep object in JavaScript.

In this article, we’ll look at how to get all keys of a deep object in JavaScript.

How to get all keys of a deep object in JavaScript?

To get all keys of a deep object in JavaScript, we can recursive traverse the object to get the keys.

For instance, we write:

const obj = {
  foo: 'bar',
  count: '3',
  counter: {
    count: '3',
  },
  baz: {
    test: "qux",
    tester: {
      name: "Ross"
    }
  }
};

const objectDeepKeys = (obj, keys = []) => {
  for (const key of Object.keys(obj)) {
    keys.push(key)
    if (typeof obj[key] === 'object' && obj[key] !== null) {
      objectDeepKeys(obj[key], keys)
    }
  }
  return keys
}

console.log(objectDeepKeys(obj))

to define the objectDeepKeys function that takes the obj object to traverse and the array of keys.

In the function, we loop through each key we get from Object.keys with a for-of loop.

And in the loop, we have keys.push(key) to append the key to keys.

If obj[key] is an object and it’s not null, we call objectDeepKeys to do the same thing in the next level.

As a result, we see ['foo', 'count', 'counter', 'count', 'baz', 'test', 'tester', 'name'] logged.

Conclusion

To get all keys of a deep object in JavaScript, we can recursive traverse the object to get the keys.