Looping through an objects properties

This post posts a snippet of code of how to loop through an objects properties in order to get the key names.

About six months ago we had some convoluted way of doing something on the backend (PHP), and in order to get something back I was give an single object with a ton of properties and I had to loop over them. For the life of me I couldn’t find any snippets of code that let me loop through an objects properties and get the actual key names… its very simple to loop through an object and get the values, thats cake…. but I was like… hmmm how do I get the key names?

So I came across Dictionary, which I always thought was just an expansion of Object, and I could never really figure out what it did that object didn’t except for the fact that as3coreLib has a Dictionary Utility class that makes it so you can loop over an object and get the keys, and its a light weight .swc file, so I used it up, and started using dictionaries for that reason, and haven’t used Generic Objects ever since, because I figured they did the same thing except Dictionary classes gave me the ability to loop through them and get the keys….

The other day I ran across some code, and thought to myself, so I use a DictionaryUtility class, why didn’t I ever think to even look through the ObjectUtil class in as3… so anyway…. there is a function in that class called getClassInfo, that will give you an array of the properties back… I felt pretty stupid after that, but needless to say I found another way to make my life easier coding….

here is a really small snippet.

var classInfoProperties:Array = ObjectUtil.getClassInfo(a[0]).properties as Array;

2 comments on this post.
  1. Ragona:

    You can use a for..in loop to get the keys in either an Object or a Dictionary:

    var myObject:Object = {foo: ‘bar’};

    for(var item in myObject)
    {
    trace(item); //traces ‘foo’
    trace(myObject[item]); //traces ‘bar’
    }

    var myDict:Dictionary = new Dictionary();

    myDict[‘foo’] = ‘bar';

    for(var dictItem in myDict)
    {
    trace(dictItem); //traces ‘foo’
    trace(myDict[dictItem]); //traces ‘bar’
    }

  2. Alida Mendez:

    Usually an excellent post next time i see this website along with other information sites you own. Recognize the value of your current skills.

Leave a comment