Tuesday, April 30, 2019

javascript - Insert Object data in HTML




How can I list the structured contents of a Javascript Object in HTML?



My object looks like this:



var lists = {
"Cars":{"Ford":false,"Ferarri":false},
"Names":{"John":true,"Harry":false},
"Homework":{"Maths":true,"Science":false,"History":true,"English":true}
}


What would the loop look like to print the keys as headers, and the property + values as an ordered list underneath?



Example:



Cars




  1. Ford = False

  2. Ferrari = False



Names




  1. John = True

  2. Harry = False



Homework




  1. Maths = True

  2. Science = False

  3. History = True

  4. English = True



I understand that I can append the object by name to HTML, but if the object is dynamic, and the key isn't known, how can I make a loop to do so?


Answer



Just got to loop, create the HTML string, and append! Say you have a container:






And your JS



var htmlString = "";
for (var key in lists) {
htmlString += "" + key + "";
htmlString += "
    ";
    for (var item in lists[key]) {
    htmlString += "
  • " + item + " = " + lists[key][item] + "
  • ";
    }
    htmlString += "
";
}

document.getElementById("container").innerHTML = htmlString;


Working demo: http://jsfiddle.net/owqt5obp/


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...