我有这样一个对象:

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


当前回答

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

你需要使用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' } } } } }
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"}}}}}

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

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

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

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

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