我有这样一个对象:

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的内容?


当前回答

JSON.stringify()

let myVar = {a: {b: {c: 1}}};
console.log(JSON.stringify( myVar, null, 4 ))

非常适合深入检查数据对象。这种方法适用于嵌套数组和带有数组的嵌套对象。

其他回答

你也可以

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

这两种用法都可以应用:

// 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));

一个简单的技巧是在运行脚本时使用调试模块添加DEBUG_DEPTH=null作为环境变量

Ex.

DEBUG=* DEBUG_DEPTH=null节点index.js

在代码中

const debug = require('debug');
debug("%O", myObject);

使用记录器

不要试图重新发明轮子

util.inspect(), JSON.stringify()和console.dir()是在浏览器控制台中播放时记录对象的有用工具。

如果你认真对待Node.js开发,你绝对应该使用记录器。使用它,您可以添加调试和监视应用程序所需的所有日志。然后只需更改日志记录器的日志级别,以只显示生产日志。

此外,他们已经解决了所有与日志相关的恼人问题,如:循环对象,格式,日志级别,多个输出和性能。

使用现代的记录器

pino是一个快速和现代的Node.js日志记录器,它有正常的默认值来处理循环对象/引用,如depthLimit和edgeLimit。它支持子日志记录器、传输和漂亮的打印输出。

此外,它有8个默认的日志级别,你可以使用customLevels选项自定义:

致命的 错误 警告 信息 调试 跟踪 沉默

安装它

npm install pino

使用它

const logger = require('pino')()

logger.info('hello world')

配置它

const logger = pino({
  depthLimit: 10,
  edgeLimit: 200,
  customLevels: {
    foo: 35
  }
});

logger.foo('hi')

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

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