Rafay Rafay - 5 months ago 25
Javascript Question

Iterate through object properties

var obj = {
name: "Simon",
age: "20",
clothing: {
style: "simple",
isDouche: 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?

I hope I'm not asking stupid questions, I couldn't find any answers.

Answer

Iterating over properties requires this additional hasOwnProperty check:

for (var property in object) {
    if (object.hasOwnProperty(property)) {
        // do stuff
    }
}

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.