How to deal with [Object] in console.log() when object hierarchy is deep

How to deal with [Object] in console.log() when object hierarchy is deep

When I use console.log() to display objects, it shows up to a certain level of hierarchy, but if it is too deep, it becomes [Object] and is not displayed.

const obj = { a: { b: { c: { d: {} } } } }
console.log(JSON.stringify(obj)) // { a: { b: { c: [Object] } } }

Use JSON.stringify() to display this.

const log = { a: { b: { c: { d: {} } } } }
console.log(JSON.stringify(log)) // {"a":{"b":{"c":{"d":{}}}}}

Third argument of JSON.stringify()

JSON.stringify has three arguments, the third of which is a numerical value “2” to be formatted. The indentation will be 2. If you specify \t as a string, it will be tabbed.

const log = { a: { b: { c: { d: {} } } } }
console.log(JSON.stringify(log, null, 2))

/*
↓ display
{
  "a": {
    "b": {
      "c": {
        "d": {}
      }
    }
  }
}
*/

console.log(JSON.stringify(log, null, '\t'))

/*
↓ display
{
        "a": {
                "b": {
                        "c": {
                                "d": {}
                        }
                }
        }
}
*/

Second argument of JSON.stringify()

The second argument specifies the key of the object of the first argument as an array of strings.

Only the key-value specified in the second argument will be displayed.

console.log(JSON.stringify({ a: 1, b: 2, c: 3 }, ['a'])) // {"a":5}

One slightly more difficult usage is to specify a callback function called “replacer.

I can’t think of many use cases for this, but if you want to display a JS Error object in console.log, you can use this replacer to display the contents of the error.

The first argument of the callback function is the object’s key, and the second argument is the object’s value. The following is an example of output in the case of an Error object.

const err = new Error('error message')

console.log(
  JSON.stringify(err, function(key, val) {
    return JSON.stringify(val, Object.getOwnPropertyNames(val)) // For Error object, key is ''.
  })
)

Object.getOwnPropertyNames()

If value is a function, key-value disappears

If the value of the object is a function, the entire key will disappear.

const log = { a: { b: { c: { d:function(){return 1;}} } } } 
console.log(JSON.stringify(log)) // { a: { b: { c: {} } } }

Using util.inspect

Since about node version 9 or so, you can use util.inspect to stringify objects.

By specifying the depth:null option, even if the hierarchy is deep and value is a function, it will be displayed.

const util = require('util')
console.log(util.inspect({a:{b:{c:{d:{e:{f:(ret)=> ret}}}}}}, {depth: null}))

コメント

Discover more from 株式会社CONFRAGE ITソリューション事業部

Subscribe now to keep reading and get access to the full archive.

Continue reading

Copied title and URL