Console.log Deep Objects

| Comments

With deep object structures, console.log can leave you wondering what’s down in the depths of the objects you’re printing out. Here’s a quick help from Node stdlib.

console.log deep objects

You can usually see the objects that you’re console.loging, and life is good:

Given:

1
2
3
4
5
const stickers = {
  are: 'fun'
}
console.log('stickers', stickers)
// Outputs: stickers { are: 'fun' }

We can see the whole object, and we’re happy. We can even do objects up to a depth of 3 sub objects, and it works great:

1
2
3
4
5
6
7
8
9
const stickers = {
  are: {
    even: {
      more: 'fun'
    }
  }
}
console.log('stickers', stickers)
// Outputs: stickers { are: { even: { more: 'fun' } } }

If, however, we have a potentially deeply-nested object, we’ll get some of our data truncated:

1
2
3
4
5
6
7
8
9
10
11
12
13
const stickers = {
  are: {
    even: {
      more: {
              than: {
                  outrageously: 'fun'
              }
          }
    }
  }
}
console.log('stickers', stickers)
// Outputs: stickers { are: { even: { more: [Object] } } }

[Object]s are cool and all, but not very informative.

To get at this information, use util.inspect from the stdlib. Here, you can set a depth option to be higher, letting you peer into those deep objects in the console:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const util = require('util')
const stickers = {
  are: {
    even: {
      more: {
              than: {
                  outrageously: 'fun'
              }
          }
    }
  }
}
console.log('stickers', util.inspect(stickers, { depth: 4 }))
// Outputs: stickers { are: { even: { more: { than: { outrageously: 'fun' } } } } }

Your data is yours again!

Comments