calvinf
calvinf

Reputation: 3924

Calculating Dictionary length in Flex

What's the best way to calculate the length of a Dictionary object in Flex?

var d:Dictionary = new Dictionary();
d["a"] = "alpha";
d["b"] = "beta";

I want to check the length which should be 2 for this Dictionary. Is there any way to do it other than looping through the objects?

Upvotes: 7

Views: 13476

Answers (6)

gbdcool
gbdcool

Reputation: 982

You can get keys of the Dictionary and check the length of keys array as below:

var d:Dictionary = new Dictionary();
d["a"] = "alpha";
d["b"] = "beta";
var count:int = DictionaryUtil.getKeys(d).length;

Upvotes: 0

Craig
Craig

Reputation: 1345

For anyone stumbling upon this now there is an update to DictionaryUtil. You can now just call..

var count:int = DictionaryUtil.getKeyCount(myDictionary);

Upvotes: 0

marketer
marketer

Reputation: 43707

There's a util function in as3corelib which can get the keys in the dictionary. You can check out DicitonaryUtil

The method is:

    public static function getKeys(d:Dictionary):Array
    {
        var a:Array = new Array();

        for (var key:Object in d)
        {
            a.push(key);
        }

        return a;
    }

So you would do getKeys(dictionary).length

Upvotes: 3

tousdan
tousdan

Reputation: 196

You could write a class around a dictionnary that controls insertions/removals so you can keep track of the key count.

Try extending proxy or just do a wrapper.

Upvotes: 0

nevets1219
nevets1219

Reputation: 7706

You can use associative arrays instead because I don't think it's possible to check the length of a Dictionary object. You could however extend the Dictionary class and add that functionality and override the corresponding methods.

Alternatively, you could loop through it each time to get the length which isn't really a good idea but is available.

var d:Dictionary = new Dictionary();
d["hi"] = "you"
d["a"] = "b"
for (var obj:Object in d) {
  trace(obj);
}
// Prints "hi" and "a"

You can also look here for information on using the "setPropertyIsEnumerable" but I believe that's more useful for objects than it is for Dictionary.

Upvotes: 1

CookieOfFortune
CookieOfFortune

Reputation: 13994

No, there is no way to check the length of an object(Dictionary is pretty much an object that supports non-String keys) other than looping through the elements.

http://www.flexer.info/2008/07/31/how-to-find-an-objects-length/

You probably don't have to worry about checking if the property is an internal one.

Upvotes: 12

Related Questions