DEV Community

Cover image for Debugging nested objects
Sibelius Seraphini for Woovi

Posted on

Debugging nested objects

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

Top comments (3)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

You might want to provide more context here? In a browser, logging such an object to the console gives an interactive output that allows inspecting of all levels. No issues at all.

I can only assume maybe you are referring to NodeJS?

Collapse
 
franklinjavier profile image
Franklin Javier 🚀

He wrote "You will get this in your terminal"

Collapse
 
tuliocalil profile image
Tulio Calil

Nice!
Another way (that I use a lot) is with JSON.stringify().

const nested = {a: {b: {c: {d: 'd'}}}};

console.table(JSON.stringify(nested, null, 2));
Enter fullscreen mode Exit fullscreen mode

Output

Works very well too.