for...in with forEach()
EasyProgramming.net tutorial on how to combine the for...in loop with for...each
by Nazmus Nasir
HTML
<!-- JavaScript Objects - The for...in loop with dynamic objects #42 -->
<p>
Welcome to the 42nd Easy JavaScript tutorial, part of <a href="http://www.easyprogramming.net">EasyProgramming.net</a>. Let's practice some more of the for...in loop and see how we can keep outputting results based on dynamic objects that we create.
</p>
<p>
Be sure to watch my array.forEach tutorial for more information on how the forEach() loop works. Let's get to it!
</p>
<h2>
Syntax of a <code>for...in</code> loop:</h2>
<p>
<code><pre>
for(property in object){
//E.g. object - person = {name:"Nazmus"};
var x = property; //name of the property itself - name
var y = object[property]; //value of the property - Nazmus
}
</pre>
</code>
</p>
<p>
<h2>
Let's practice:</h2>
<span id="output"></span>
<br /><br />
JavaScript
var person = function(name,city,state,website,language,job){
this.name = name,
this.city = city,
this.state = state,
this.website = website,
this.language = language,
this.job = job
}
var output = document.getElementById("output");
var x = [
new person('Nazmus','Boston','Massachusetts','EasyProgramming.net','JavaScript','Developer'),
new person('Bill','Seattle','Washington','Microsoft.com','.NET','Billionaire'),
new person('Mark','Honolulu','Hawaii','Facebook.com','.PHP','Also Billionaire')
]
x.forEach(function(item,i){
for(p in item){
output.innerHTML += p + ': ' + item[p] + '<br />';
}
output.innerHTML += '<br />';
});