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
- Ford = False
- Ferrari = False
Names
- John = True
- Harry = False
Homework
- Maths = True
- Science = False
- History = True
- 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?
-
@Quentin: This question isn't only about looping through an object, it's also about appending elements to HTMLCerbrus– Cerbrus2014年10月31日 13:45:22 +00:00Commented 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.Quentin– Quentin2014年10月31日 13:46:41 +00:00Commented Oct 31, 2014 at 13:46
-
@Quentin: Oh, you're right. Nevermind what I said :-)Cerbrus– Cerbrus2014年10月31日 13:47:12 +00:00Commented Oct 31, 2014 at 13:47
-
@tymeJV: Don't abuse your JS gold badge just because you want to answer a question -.-Cerbrus– Cerbrus2014年10月31日 14:02:50 +00:00Commented Oct 31, 2014 at 14:02
-
@Cerbrus -- Well I did re-open it based on your initial comment, suppose I should've read more :\tymeJV– tymeJV2014年10月31日 14:07:38 +00:00Commented Oct 31, 2014 at 14:07
1 Answer 1
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/
answered Oct 31, 2014 at 13:47
tymeJV
105k14 gold badges165 silver badges158 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
Maurice Perry
It works for the example, so +1, to be safe however, the value should be escaped.
tymeJV
@MauricePerry -- What do ya mean?
CodeSlow
Thanks @tymeJV didn't think about a loop inside a loop!
Maurice Perry
@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.
CodeSlow
@tymeJV is it possible to use ".append" in this scenario?
default