Thiago Goncalves
Thiago Goncalves

Reputation: 1

How to Convert a string to the name of an Object

I am trying to access the "ID's" of the Object data but for the compiler does not like that... what is the right way to do this.

var objectName:Object = {ID:2, IDName:"this_is_string"};

var target:string="objectName";

trace(target.IDName");  // does not work...
trace("target.ID");

any helps would be greatly appreciated.

Upvotes: 0

Views: 527

Answers (3)

ZicZac
ZicZac

Reputation: 1

How to convert a string to an object identifier and then retrieve/get property values for that object? There is two ways to do this in ActionScript:

  1. We can use the eval() function:

eval(targetAsString.IDName); or eval(_root.targetAsString.IDName);

  1. We can use the array-access operator:

_root[targetAsString].IDName; or _root[targetAsString]["IDName"];

Notice how I use a string to target the value of the property, by using array-access operator [] multiple times.

I would recommend to use the the array-access operator over the eval() function because it's faster and less processor intensive. It's also a more secure solution.

Upvotes: 0

Spiros
Spiros

Reputation: 1

That works:

trace (eval(target).IDName)

Upvotes: 0

Richard D
Richard D

Reputation: 5685

Try:

trace( [target].IDName );

Upvotes: 0

Related Questions