我有这样一个对象:

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


当前回答

这两种用法都可以应用:

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

其他回答

节点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文档中查看更多详细信息。

使用记录器

不要试图重新发明轮子

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')
const myObject = {
   "a":"a",
   "b":{
      "c":"c",
      "d":{
         "e":"e",
         "f":{
            "g":"g",
            "h":{
               "i":"i"
            }
         }
      }
   }
};
console.log(JSON.stringify(myObject));

输出:

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

如果你正在寻找一种方法来显示数组中隐藏的项,你必须传递maxArrayLength: Infinity

console.log(util.inspect(value, { maxArrayLength: Infinity }));