Reputation: 105
I want Iterate through all object properites. I was trying to do this by using
for( var key in obj)
But that didnt give me all properties. For example, there is no key 'click'. But when i try to do
obj['click']
i got something.
I am trying to do this on IE7
Upvotes: 3
Views: 3348
Reputation: 53705
For/in runs over all enumerable properties, including those inherited from ancestor prototypes. If you just want the ones for "your object", use Object.keys()
:
Object.keys(yourobject).forEach(function(propertyName) {
var value = yourobject[propertyName];
console.log(propertyName + ":", value);
});
Upvotes: 1
Reputation: 35970
The for .. in
loop iterates over all enumerable
properties, not over all properties.
So I would suspect either the click
is not enumerable or you missed something.
Example on how to set a property which will not be available via the for .. in
loop:
var obj = {};
Object.defineProperty(obj, "stealth", {
enumerable: false,
value: "you don't iterate over me"
});
// obj.stealth === "you don't iterate over me"
for (var i in obj) {
// Loop will not enter here
}
You can test whether property is enumerable (i.e. will be accessible in a for .. in
loop) using Object.propertyIsEnumerable()
method:
obj.propertyIsEnumerable('stealth') === false
Upvotes: 3