3

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

John Smith
  • 105
  • 1
  • 2
  • 10
  • What is this __something__ you're getting? – Ofir Israel Aug 31 '13 at 13:53
  • If you are iterating correctly, perhaps you are using the `hasOwnProperty`, like http://stackoverflow.com/a/921808/613130, so you are skipping properties defined in "parent" objects. – xanatos Aug 31 '13 at 14:01

2 Answers2

3

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
kamituel
  • 34,606
  • 6
  • 81
  • 98
1

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);
});
Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153