0

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?

CodeSlow
  • 133
  • 1
  • 7
  • @Quentin: This question isn't only about looping through an object, it's also about appending elements to HTML – Cerbrus Oct 31 '14 at 13:45
  • @Cerbrus — The last paragraph of the question says that the appending to HTML part is already sorted. If that isn't what the OP intended to say, then the question is too broad anyway. – Quentin Oct 31 '14 at 13:46
  • @Quentin: Oh, you're right. Nevermind what I said :-) – Cerbrus Oct 31 '14 at 13:47
  • @tymeJV: Don't abuse your JS gold badge just because you want to answer a question -.- – Cerbrus Oct 31 '14 at 14:02
  • @Cerbrus -- Well I did re-open it based on your initial comment, suppose I should've read more :\ – tymeJV Oct 31 '14 at 14:07

1 Answers1

4

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

<div id="container"></div>

And your JS

var htmlString = "";
for (var key in lists) {
    htmlString += "<span>" + key + "</span>";
    htmlString += "<ul>";
    for (var item in lists[key]) {
        htmlString += "<li>" + item + " = " + lists[key][item] + "</li>";
    }
    htmlString += "</ul>";
}

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

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

tymeJV
  • 103,943
  • 14
  • 161
  • 157