1

Is there an equivalent of php's array_flip() in flash actionscript 3? Here's the definition for array_flip:

array_flip() returns an array in flip order, i.e. keys from trans become values and values from trans become keys.

If not, what is the least verbose and most efficient way to achieve the same results as array_flip() in actionscript 3?

John
  • 32,403
  • 80
  • 251
  • 422
  • good question. although i'm curious what situation would require inverting key/value pairs? – Chunky Chunk Mar 25 '12 at 20:56
  • sometimes i have arrays like arr["en"]="English"; arr["fr"]="French"; Sometimes I know the key, and want the value, other times I know the value and want the key. array_flip makes things easy like array_flip($arr)["English"] will give me the key. – John Mar 25 '12 at 21:09
  • ah ha! so in this situation with AS3 you wouldn't necessirly need to invert the key/value pairs, you could just use some AS3 statements: answer below. – Chunky Chunk Mar 25 '12 at 21:16

2 Answers2

1

Use this function:

function flip(obj:Object):Object
{
    var base:Object = {};

    for(var i:String in obj)
    {
        base[obj[i]] = i;
    }

    return base;
}

Demo:

var array:Array = [];

array["a"] = "a1";
array["b"] = "b2";
array["c"] = "c3";

var newObj:Object = flip(array);

trace(newObj.b2); // b
Marty
  • 39,033
  • 19
  • 93
  • 162
0

you can use the for each...in statement to get the value associated to a key and use the for...in statement to get the key associated to a value.

Chunky Chunk
  • 16,553
  • 15
  • 84
  • 162