How To Loop Through Objects In JavaScript
erics, Posted May 15th, 2011 at 3:27:30pm
Coming from the Perl world, I wanted to emulate the following code in JavaScript:
1 2 3 4 5 6 7 |
my $myHash = { 'foo' => 'Hello', 'bar' => 'World', }; foreach my $myKey (keys %$myHash) { print $myKey,'=',$myHash->{$myKey}; } |
What I found is that JavaScript uses “Objects” to contain hash-style data:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Define the hash object on the fly var myHash = { foo: "Hello", bar: "World" }; // loop through all keys for (var myKey in myHash) { alert(myKey + '=' + myHash[myKey]); } // access a key individually alert('foo=' + Hash.foo); alert('bar=' + Hash.bar); |
Also, one may use variables as key names by using the square-bracket notation, which evaluates variables first:
1 2 3 4 |
var myVar = 'test'; //These two lines are equivalent as long as myVar is 'test': myHash[myVar] = 'theValue'; myHash.test = 'theValue'; |
Leave Your Comment
All fields marked with "*" are required.