views:

121

answers:

1

Hey, I've got a question about refrencing properties from an actionscript object.

If i've got the following object named "groups"...

group1
   item1 = sampledata1 
   item2 = sampledata2
   item3 = sampledata3
group2
   item1 = sampledata4
   item2 = sampledata5
   item3 = sampledata6

I would access group1/item2 by typing "groups.group1.item2"

How would I create a method, where I can pass in the key in string form, and retrieve the data at that node. For example

groups.group1.item2 would return sampledata2

and

getItem("group1.item2"); would also return sampledata2

I think this is possible using eval(), but I believe that was removed in AS 3.0 which i'm using. Is there any other way to do this? Thanks.

+3  A: 

Use Objects the way you would use hashes.

You can initialize objects this way:

groups = 
{
   "group1":
   {
       "item1":sampledata1,
       "item2":sampledata2
   },
   "group2":
   {"item1":sampledata1...
   }
};

Or using brackets:

groups = new Object();
groups["group1"] = new Object();
groups["group1"]["item1"] = sampledata1;

Access is done like this:

groups["group1"]["item1"]

hope that helps.

CookieOfFortune
correct answer ... yet, you don't need to be JSON conform ... what i mean, is rather than using strings as keys, you can use identifiers ... i.e. { "key":<value> } is equivalent to { key:value } ... and to maybe complete your answer with a clear statement: someObject["someProperty"] is equivalent to someObject.someProperty, except that the latter is faster if someObject's type is known, and someProperty is defined by someObject's class ... greetz
back2dos
yes, you're correct, I dunno what I was thinking when I typed that.
CookieOfFortune
oh yes, I was doing some of that code at the moment and my property had spaces in it, so I don't think you can do that with the non-string notation.
CookieOfFortune