AS3 - Looping over properties of a class (property enumeration)

In AS1 & AS2 you could use a for..in loop to enumerate the properties of an Object for introspection. Given that everything in Actionscript extends the Object class I expected that you could do a for..in loop over the properties of a Class. For example if you wanted to do a loop over all the properties in a value object.

//Sample code to trace the properties of an object
var myVO = new MyVO();
for(i in myVO){
trace(i+':'+myVO[i]);
}

However in AS3 this code will not work as expected (assuming that MyVO is not a dynamic class). I've come across this a couple of times in the last couple of weeks a yesterday found the solution to it.

There is a new function which gives all the introspection data for classes in AS3 - flash.util.describeType() which returns an XML Object.

//Get an XML description of this class
flash.utils.describeType(myVO);

To do the previous looping over the properties it could be used as follows:

//Get an XML description of this class
//and return the variable types as XMLList with e4x
var varList:XMLList = flash.utils.describeType(myVO)..variable;

for(var i:int; i < varList.length(); i++){
//Show the name and the value
trace(varList[i].@name+':'+ myVO[varList[i].@name]);
}

There is one other thing to catch you out though. If you make your variables [Bindable] or use getters & setters they will not show up as "variable". They will show up instead as "accessor" which is something to be aware of.

Hope it helps. Cheers, Mark

Comments
Theo's Gravatar You could probably do something like this to catch getters, setters and bindable properties too:

var def : XML = describeType(obj);

var properties : XMLList = def..variable.@name + def..accessor.@name;

for each ( var property : String in properties ) {
trace(property + ": " + obj[property]);
}

I haven't compiled nor tested the above, but I have done something similar a few times.
# Posted By Theo | 2/7/08 5:40 PM
Mark Lynch's Gravatar Hi Theo,
Thanks for the tip - I tried it out and it works great. I'm getting to like E4X more the more I use it.

Cheers,
Mark
# Posted By Mark Lynch | 2/7/08 8:08 PM
montana's Gravatar muchas gracias! exactly what I was looking for.
# Posted By montana | 5/14/08 7:36 AM
Scott Ysebert's Gravatar Thanks for this. I was ripping out my hair to try and figure out what was up with AS3 and the ability to loop through my objects properties.
# Posted By Scott Ysebert | 5/16/08 10:59 PM
SmartPlugs Design's Gravatar This did the trick and worked perfectly! Thanks for posting these!
# Posted By SmartPlugs Design | 6/29/08 9:23 PM
BlogCFC was created by Raymond Camden. This blog is running version 5.1.004.