Mar 31, 2009
Obtaining Object Properties and Values in Flash
First, I have to say this is nothing special or ground breaking. I’m mainly putting this up to hopefully remind myself of how I did this and possibly find a better way in case I need to do this in the future.
Now with that out of the way I’ll explain what I did and how I solved it. I was working on a project and in one moment I had to obtain a series of properties and it’s values from an object such as this:
var o:Object = {time: 1, color: "red", food: "cereal"};
The first thing I did was use a for… each loop. It gave me the values but I couldn’t get the actual property name. So, after a quick google search I realized I could use a for… in loop. This allowed me to get each property instead of the value. I could then use that property name to obtain it’s value and have the best of both worlds. Here’s some code to show you what I mean:
for (var prop:Object in o) { trace(prop + ': ' + o[prop]); } // results // color: red // time: 1 // food: cereal
Now, there are still a few things that can be an issue. If you run that script over again the order will be different. This may or may not make any difference, but it’s still something to keep in mind.
I have to say in regards to how I handled this situation. It was specific to my project and now looking back at it this wasn’t the best choice. In one way, it was open but also very restrictive and caused at times some special case handling.