This question already has an answer here:
How do I enumerate the properties of a JavaScript object?
I actually want to list all the defined variables and their values, but I've learned that defining a variable actually creates a property of the window object.
Use a
for..in
loop to enumerate an object's properties, but be careful. The enumeration will return properties not just of the object being enumerated, but also from the prototypes of any parent objects.To avoid including inherited properties in your enumeration, check
hasOwnProperty()
:Edit: I disagree with JasonBunting's statement that we don't need to worry about enumerating inherited properties. There is danger in enumerating over inherited properties that you aren't expecting, because it can change the behavior of your code.
It doesn't matter whether this problem exists in other languages; the fact is it exists, and JavaScript is particularly vulnerable since modifications to an object's prototype affects child objects even if the modification takes place after instantiation.
This is why JavaScript provides
hasOwnProperty()
, and this is why you should use it in order to ensure that third party code (or any other code that might modify a prototype) doesn't break yours. Apart from adding a few extra bytes of code, there is no downside to usinghasOwnProperty()
.I think an example of the case that has caught me by surprise is relevant:
But to my surprise, the output is
Why? Another script on the page has extended the Object prototype:
Here's how to enumerate an object's properties:
You can use the
for
of loop.If you want an array use:
Object.keys(object1)
Ref. Object.keys()
Simple JavaScript code:
jQuery:
The standard way, which has already been proposed several times is:
However Internet Explorer 6, 7 and 8 have a bug in the JavaScript interpreter, which has the effect that some keys are not enumerated. If you run this code:
If will alert "12" in all browsers except IE. IE will simply ignore this key. The affected key values are:
isPrototypeOf
hasOwnProperty
toLocaleString
toString
valueOf
To be really safe in IE you have to use something like:
The good news is that EcmaScript 5 defines the
Object.keys(myObject)
function, which returns the keys of an object as array and some browsers (e.g. Safari 4) already implement it.