Reputation: 154
Because AS3 does not include eval()
I am confused on how to access objects dynamically.
I want to refer to a specific property of an object but the name of the object and the property's name are not know until runtime. I've tried my best to figure it out, but I'm at a loss. Here is some code to illustrate the problem:
trace(ObjectName.PropertyName);
//object definitions
var myObj1:Object = {
myProp1 : "cat",
myProp2 : "dog",
myProp3 : "fish"
};
var myObj2:Object = {
myProp1 : "carrot",
myProp2 : "potato",
myProp3 : "celery"
};
//tests
trace( myObj1.myProp2 ); //dog
trace( myObj2.myProp3); //celery
trace( eval("myObj" + i +".myProp" + j));
//example iterators
var i:int = 2;
var j:int = 3;
trace( "myObj"+i+".myProp"+j); //outputs expected string, myObj2.myProp3
trace( getChildByName(["myObj" +i]).getChildByName(["myObj" +j]) ); //error
trace( this["myObj" +i].this["myProp" +j] ) //error
var currObj:String = getChildByName(["myObj" +i]);
var currProp:String = getChildByName(["myProp" +j]);
trace (currObj.currProp); //lots of errors
Thanks For the Help :)
Upvotes: 0
Views: 90
Reputation: 640
The getChildByName is only for display list. You can use [] in object.
Change this
trace( this["myObj" +i].this["myProp" +j] ) //error
To this
trace( this["myObj" +i]["myProp" +j] ) //Working
Upvotes: 1
Reputation: 12431
You're almost there with your third attempt using the array access method:
trace( this["myObj" + i]["myProp" + j] ) // no error
Upvotes: 2