How to show objects inside html elements like console?

半城伤御伤魂 提交于 2019-12-02 18:11:53

问题


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 returns "[object object]" inside the paragraph. Is there a way to show it like console.log method inside the paragraph?.
Here is my code :

var obj = {
  subobj: {prop1: "value1", prop2: "value2", prop3: "value3"},
};

var var1 = "subobj";

function func() {
  for (x in obj) {
    if (var1 == x) {
      // i want it to be shown like the console.log method
      // console.log(obj[x])
      document.getElementById("demo").innerHTML = obj[x];
    }
  }
};

func()

回答1:


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




回答2:


Try and use this:

document.getElementById("demo").innerHTML = JSON.stringify(obj[x])



回答3:


Maybe this helps:

var obj = {"objects":[
    {"prop1": "obj1 value1", "prop2": "obj1 value2"},
    {"prop1": "obj 2 value1", "prop2": "obj2 value2"}
]};

function func() {
    var html = "";
    for (var i=0; i < obj.objects.length; i++) {
            // i want it to be shown like the console.log method
            // console.log(obj[x])
        html += "<p>" + obj.objects[i].prop1 + obj.objects[i].prop2  + "</p>";

        }

    document.getElementById("demo").innerHTML = html;
    }
func();

You used "obj[x]", but you don't have an array of objects in your obj. And also this is better because you cache the html in a string and only interact with the DOM once, when you call "document.getElementById("demo").innerHTML = html;".

Good luck!



来源:https://stackoverflow.com/questions/35537074/how-to-show-objects-inside-html-elements-like-console

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!