繁体   English   中英

通过节点显示javascript对象的格式

[英]Display formating of javascript object, through node

我有一段时间对此感到困惑。 我们来看看这个简单的对象:

let animalList = {
  animals : ["dog","cat","horse"],
  colors : ["blue","red"]
};

console.log(animalList);

它给了我这个输出:

{ animals: [ 'dog', 'cat', 'horse' ],
  colors: [ 'blue', 'red' ] }

假设我想要这个输出(我理解它纯粹是化妆品):

{
  animals: [ "dog", "cat", "horse" ],
  colors: [ "blue", "red" ]
}

节点在哪里存储它的显示属性? (要使用的引号,显示对象的间距和换行符,等等)

您可以使用JSON.stringifymdn )进行某些格式化:

 let animalList = { animals : ["dog","cat","horse"], colors : ["blue","red"] }; console.log(JSON.stringify(animalList, null, 2)); 

但是要自定义新行的处理方式,您必须创建自己的obj->字符串函数,例如:

 let prettyPrint = (obj, indent = 0, indentStep = 2) => { if (Array.isArray(obj)) return `[ ${obj.map(a => prettyPrint(a, indent + 1, indentStep)).join(', ')}]`; if (typeof obj === 'string') return `"${obj}"`; if (typeof obj === 'number') return number; if (typeof obj === 'undefined') return 'undefined'; if (typeof obj === 'object') { let spaces = ' '.repeat((indent + 1) * indentStep); let inside = Object.entries(obj).map(([key, value]) => `${spaces}${key}: ${prettyPrint(value, indent + 1, indentStep)}`); return `{\\n${inside.join(',\\n')}\\n},`; } }; let animalList = { animals: ["dog", "cat", "horse"], colors: ["blue", "red"] }; console.log(prettyPrint(animalList)); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM