我有这样一个对象:

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

其他回答

简单的选择:

console.log ' % ', myObject);

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

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

试试这个:

console.dir(myObject,{depth:null})

您可以使用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文档中查看更多详细信息。

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"}}}}}