Eric Jones
Eric Jones

Reputation: 154

AS3: Refer to a property of an object when both the objects name and the property name aren't known 'till runtime?

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:

In the following code, we can access properties like
this: 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

But I want to access them dynamically w/ two different iterators like
this: trace( eval("myObj" + i +".myProp" + j));

code I've tried:

//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

Answers (2)

Nambew
Nambew

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

net.uk.sweet
net.uk.sweet

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

Related Questions