var obj = {
name: "Simon",
age: "20",
clothing: {
style: "simple",
hipster: false
}
}
for(var propt in obj){
alert(propt + ': ' + obj[propt]);
}
How does the variable propt
represent the properties of the object? It's not a built-in method, or property. Then why does it come up with every property in the object?
Iterating over properties requires this additional
hasOwnProperty
check:It's necessary because an object's prototype contains additional properties for the object which are technically part of the object. These additional properties are inherited from the base object class, but are still properties of
object
.hasOwnProperty
simply checks to see if this is a property specific to this class, and not one inherited from the base class.Dominik's answer is perfect, I just prefer to do it that way, as it's cleaner to read:
If running Node I'd recommend:
Your
for
loop is iterating over all of the properties of the objectobj
.propt
is defined in the first line of your for loop. It is a string that is a name of a property of theobj
object. In the first iteration of the loop,propt
would be "name".Girls and guys we are in 2017 and we do not have that much time for typing... So lets do this cool new fancy ECMAScript 2016:
What for..in loop does is that it creates a new variable (var someVariable) and then stores each property of the given object in this new variable(someVariable) one by one. Therefore if you use block {}, you can iterate. Consider the following example.