我有这样一个对象:

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

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

其他回答

你需要使用util.inspect():

const util = require('util')

console.log(util.inspect(myObject, {showHidden: false, depth: null, colors: true}))

// alternative shortcut
console.log(util.inspect(myObject, false, null, true /* enable colors */))

输出

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

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

Ex.

DEBUG=* DEBUG_DEPTH=null节点index.js

在代码中

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

我觉得这可能对你有用。

const myObject = { “一”:“一”, " b ": { “c”:“c”, " d ": { “e”:“e”, " f ": { “g”:“g”, " h ": { “我”:“我” } } } } }; console.log (JSON。stringify(myObject, null, '\t'));

如本回答所述:

JSON。Stringify的第三个参数定义了空格插入 打印格式。它可以是字符串或数字(空格数)。

您可以简单地向对象添加一个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))

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

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