Debugging nested objects

Sibelius Seraphini - Jul 20 '23 - - Dev Community

Everybody uses console.log to debug if a given state of your program is as expected.
However console.log won't work to debug every variable.
If the variable is an object with many nested levels, all the levels won't show up in your output

If you try to debug this variable:

const nested = {
    a: {
      b: {
        c: {
          d: 'd',
        }
      }
    }
  };
Enter fullscreen mode Exit fullscreen mode

You will get this in your terminal

{ a: { b: { c: [Object] } } }
Enter fullscreen mode Exit fullscreen mode

This is not so helpful if you need to know what is inside c property.

Showing up all object property levels

We have this function debugConsole, that will show all nested levels in the object, and also add colors if available.

import util from 'util';

export const debugConsole = (obj: Record<string, unknown>) => {
  console.log(
    util.inspect(obj, {
      showHidden: false,
      depth: null,
      colors: true,
      showProxy: false,
    }),
  );
};
Enter fullscreen mode Exit fullscreen mode

The output is like this:

nested-log

In Conclusion

At Woovi, we don't solve the same problem twice.
We abstract and make it easy for the next developer.
A simple function can increase the productivity of your team.


Woovi
Woovi is a Startup that enables shoppers to pay as they like. To make this possible, Woovi provides instant payment solutions for merchants to accept orders.

If you want to work with us, we are hiring!


Photo by Hudson Hintze on Unsplash

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player