首页 > 解决方案 > 通过节点显示 javascript 对象的格式

问题描述

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

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

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

标签: javascriptobject

解决方案


您可以使用JSON.stringify( mdn ) 进行一些格式设置:

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

console.log(JSON.stringify(animalList, null, 2));

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

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


推荐阅读