我有这样一个对象:

const myObject = {
   "a":"a",
   "b":{
      "c":"c",
      "d":{
         "e":"e",
         "f":{
            "g":"g",
            "h":{
               "i":"i"
            }
         }
      }
   }
};

但是当我尝试使用console.log(myObject)显示它时,我收到这样的输出:

{ a: 'a', b: { c: 'c', d: { e: 'e', f: [Object] } } }

我怎样才能得到完整的对象,包括属性f的内容?


当前回答

您可以简单地向对象添加一个inspect()方法,该方法将覆盖console.log消息中的对象表示

eg:

var myObject = {
   "a":"a",
   "b":{
      "c":"c",
      "d":{
         "e":"e",
         "f":{
            "g":"g",
            "h":{
               "i":"i"
            }
         }
      }
   }
};
myObject.inspect = function(){ return JSON.stringify( this, null, ' ' ); }

然后,您的对象将在console.log和node shell中按要求表示


更新:

对象。Inspect已弃用(https://github.com/nodejs/node/issues/15549)。使用myObject [util.inspect。自定义):

const util = require('util')

var myObject = {
  /* nested properties not shown */
}

myObject[util.inspect.custom] = function(){ return JSON.stringify( this, null, 4 ); }


console.log(util.inspect(myObject))

其他回答

这两种用法都可以应用:

// more compact, and colour can be applied (better for process managers logging)
console.dir(queryArgs, { depth: null, colors: true });

// get a clear list of actual values
console.log(JSON.stringify(queryArgs, undefined, 2));

也许控制台。Dir就是你所需要的。

http://nodejs.org/api/console.html#console_console_dir_obj

使用实效。检查obj并将结果字符串打印到标准输出。

如果您需要更多的控制,请使用util选项。

另一个简单的方法是将其转换为json

console.log('connection : %j', myObject);

节点REPL有一个内置的解决方案来覆盖对象的显示方式,请参见这里。

REPL模块内部在打印值时使用util.inspect()。 然而,实效。Inspect将调用委托给对象的Inspect () 函数,如果有的话。

您可以使用JSON。Stringify,并获得一些漂亮的缩进,以及可能更容易记住语法。

console.log(JSON.stringify(myObject, null, 4));

{
    "a": "a",
    "b": {
        "c": "c",
        "d": {
            "e": "e",
            "f": {
                "g": "g",
                "h": {
                    "i": "i"
                }
            }
        }
    }
}

第三个参数设置缩进级别,因此您可以根据需要进行调整。

如果需要,请在JSON stringify MDN文档中查看更多详细信息。