PDA

View Full Version : Dynamic property name


WallArcher
09-27-2006, 11:35 PM
Hi,

Is there any way to change a property / variable key and not touching it's value?

An example of what i'm trying to do:


//Create 2 string variables and an Object.

var key1:String = "k1";
var key2:String = "k2";
var myObject:Object = new Object();

//Create a new property for myObject:

myObject[key1] = "some string";

//The slow way:

delete myObject[key1]; //nolonger needed
myObject[key2] = "some string"; //allocating new memory greatly slows the app

//A fictional method:

myObject.changePropertyName(key1, key2);
trace(myObject[key2]); //should trace "some string"


Now, is it possible to change from key1 to key2 without first having to delete and reallocate memory for key1's original value? Basically treating the property as a pointer. I really need this because it would greatly speed up an app i'm working on.

Thanks.

nirth
09-28-2006, 06:18 PM
You can use 2 Dictionaries(or even objects) as collections. first one for keys, and second for values.

//Swapable.as
package test
{
import flash.utils.Dictionary;

public class Swapable
{
private var keys:Dictionary = new Dictionary();
private var values:Dictionary = new Dictionary();
private var keyCounter:uint = 0;

public function Swapable()
{
}

public function add(key:Object,item:Object):void
{
var count:uint = keyCounter++;
keys[key] = count;
values[count] = item;
}

public function swapKeys(key1:Object,key2:Object):void
{
var tempKey1:uint = keys[key1];
keys[key1] = keys[key2];
keys[key2] = tempKey1;

}

public function getItem(key:Object):*
{
try
{
return values[keys[key]];
}catch(e:Error)
{
trace(e.message);
}
}
}
}

usage:

var col:ModifiableKeys = new ModifiableKeys();
col.add("a","aaa");
col.add("b","bbb");
col.add("c","ccc");

trace(col.getItem("a"));
trace(col.getItem("b"));
trace(col.getItem("c"));

col.swapKeys("a","c");

trace(col.getItem("a"));
trace(col.getItem("c"));

Then if you want [ ] access, you can extend mx.utils.Proxy class, and implement this ability