How to show objects inside html elements like console?

后端 未结 3 1876
时光取名叫无心
时光取名叫无心 2021-01-26 10:40

I wanna show the whole object inside a paragraph called \"demo\", and i want the object to be shown similar to the way that it will be in the console. But instead of that it ret

3条回答
  •  没有蜡笔的小新
    2021-01-26 10:58

    You can just stringify the whole object rather than looping through each key/value pair and put the result in a pre element:

    function func(obj) {
    
      // null refers to an optional replacer function which we won't
      // use in this instance. 2 is an optional parameter to set the 
      // indentation, in this case 2 spaces
      var json = JSON.stringify(obj, null, 2);
      document.getElementById("demo").innerHTML = json;
    };
    

    OUTPUT

    {
      "subobj": {
        "prop1": "value1",
        "prop2": "value2",
        "prop3": "value3"
      }
    }
    

    DEMO

提交回复
热议问题