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?

5
  • @Quentin: This question isn't only about looping through an object, it's also about appending elements to HTML Commented Oct 31, 2014 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. Commented Oct 31, 2014 at 13:46
  • @Quentin: Oh, you're right. Nevermind what I said :-) Commented Oct 31, 2014 at 13:47
  • @tymeJV: Don't abuse your JS gold badge just because you want to answer a question -.- Commented Oct 31, 2014 at 14:02
  • @Cerbrus -- Well I did re-open it based on your initial comment, suppose I should've read more :\ Commented Oct 31, 2014 at 14:07

1 Answer 1

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/

Sign up to request clarification or add additional context in comments.

5 Comments

It works for the example, so +1, to be safe however, the value should be escaped.
@MauricePerry -- What do ya mean?
Thanks @tymeJV didn't think about a loop inside a loop!
@tymeJV: the strings could contain special characters such as < or &, in which case you would produce invalid HTML. It's not the case in this particular example though.
@tymeJV is it possible to use ".append" in this scenario?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.