Calculating Dictionary length in Flex

13,408

Solution 1

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.

Solution 2

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

Solution 3

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.

Share:
13,408
Pushkar Mahajan
Author by

Pushkar Mahajan

I am a Principal Front-End Engineer in Northern Idaho.

Updated on June 14, 2022

Comments

  • Pushkar Mahajan
    Pushkar Mahajan almost 2 years

    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?

  • Donal Tobin
    Donal Tobin over 14 years
    This actually cretes an array and adds each element to it so this is very expensive to do (in memory and time)
  • Donal Tobin
    Donal Tobin over 14 years
    Here is the code to loop as notbody else provided it: '[ public static function getLen(d:Dictionary):int { var i:int = 0; for (var key:Object in d) { i++; } return i; } ]
  • Pushkar Mahajan
    Pushkar Mahajan almost 14 years
    Do you have information about when this became available or a link to documentation? There's not much information out there about this.
  • Craig
    Craig almost 14 years
    No I don't. I know that it's available in Flex 3.5 and in 4, probably even as far back as 3. I was just looking for this answer and someone on here mentioned DictionaryUtil so I did auto-complete on the functions available in it and stumbled upon this.
  • Rudy
    Rudy over 12 years
    I'm using Flex 4 and can't get this API. But there is DictionaryUtil.getItemCount in Flit library. code.google.com/p/flit/source/browse/trunk/flit/src/obecto/…