<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Traversing Objects</title>
<script type="text/javascript">
//you can place js code below in this article here
</script>
</head>
<body>
</body>
</html>
Creating an object in javascript and traversing it
//suppose you have a object named Box
var Box = {};
//Inside the first box you have text. Anything in quotes is a string in programming.
//let's call each one(known as property) a thingx and have it hold some text.
//thing1 equal to text "This is thing one"
Box.thing1 = "This is thing one";
//thing2 equal to text "This is thing two"
Box.thing2 = "This is thing two";
//thing3 equal to text "This is thing three"
Box.thing3 = "This is thing three";
//Can an object have another object? Sure, why not?
Box.AnotherBox = {};
//Can that object inside have a property? Sure, why not?
Box.AnotherBox.thing4 = "This is thing four inside another box object";
//Now let's go through this object Box;
//we need to hold the items in something while we go through the box.
var name;
var anothername;
//use name to hold each item in box
for(name in Box){
//if Box with a item name is a string
if (typeof Box[name] == "string") {
//show an alert displaying what it is.
alert(Box[name]);
}
//if Box with a item name is an object
if (typeof Box[name] == "object") {
//use anothername to hold each item in name used already
for(anothername in Box[name]){
//show an alert displaying what it is.
alert(Box[name][anothername]);
}
}
}
Place the above javascript code inside script tag in your html file mypage.html. Open the file in Google Chrome browser and see what it does.