打印嵌套的复杂对象

时间:2016-06-22 09:52:56

标签: javascript json nested

我有物件。它们是嵌套的,我实际上不知道对象中包含的参数是什么。 例如,它可以是

{
  "option1": "value1",
  "option2": "value2",
  "option3": {
    "suboption1": "subvalue1",
    "suboption2": {
       "subsuboption1": "subsubvalue1"
    }
  },
  "option4": "value4"
}

我需要打印这个对象,如:

<span class="depth-0"><b>option1</b>: value1</span>
<span class="depth-0"><b>option2</b>: value2</span>
<span class="depth-0"><b>option3</b>:</span>
<span class="depth-1"><b>suboption1</b>: subvalue1</span>
<span class="depth-1"><b>suboption2</b>:</span>
<span class="depth-2"><b>subsuboption1</b>: subsubvalue1</span>
<span class="depth-0"><b>option4</b>: value4</span>

这看起来像一个简单的任务,但我对深度上的缩进有一个很大的问题。也许有人有类似的问题。 我在我的项目中使用javascript和lodash lib。 我的模板中需要一些功能。

2 个答案:

答案 0 :(得分:1)

如何使用JSON.stringify(),根据您的需要提供space参数"--"或标签:

&#13;
&#13;
console.log(JSON.stringify({
  "option1": "value1","option2": "value2",
  "option3": {
    "suboption1": "subvalue1",
    "suboption2": {
       "subsuboption1": "subsubvalue1"
    }
  },
  "option4": "value4"
}, null, '--'));
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以尝试以下

&#13;
&#13;
var object = {
  "option1": "value1",
  "option2": "value2",
  "option3": {
    "suboption1": "subvalue1",
    "suboption2": {
      "subsuboption3": "subsubvalue3"
    }
  },
  "option4": "value4"
};




function paint(obj, level) {
  for (var key in obj) {
    if (typeof obj[key] === "object") {
      console.log('<span class="depth-"' + level +'><b>'+key + '</b>: </span>');
      paint(obj[key], level + 1);
    } else {
      console.log('<span class="depth-"' + level + '><b>'+key + '</b>: '+ obj[key]+'</span>');

    }
  }
}


paint(object, 0);
&#13;
&#13;
&#13;