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?
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