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?
It's the
for...in statement
(MDN, ECMAScript spec).You can read it as "FOR every property IN the
obj
object, assign each property to the PROPT variable in turn".Objects in JavaScript are collections of properties and can therefore be looped in a for each statement.
You should think of
obj
as an key value collection.To further refine the accepted answer it's worth noting that if you instantiate the object with a
var object = Object.create(null)
thenobject.hasOwnProperty(property)
will trigger a TypeError. So to be on the safe side, you'd need to call it from the prototype like this:Also adding the recursive way:
Usage: