Accessing data from structure

33 views
Skip to first unread message

Keith McDonald

unread,
Aug 19, 2014, 4:09:31 AM8/19/14
to haxe...@googlegroups.com
If I have a structure like so

a: {
     b: {
             c: {
                      d:e
                  }
        }
}

is there an easy way to access d (via a series of string variables)? I see there is Reflect.field which can get a field; however, I was hoping to access it in a map manner like
a["b"]["c"]["d"] since "b","c","d" might be different values.

If I can't access d in such a way - is there a way to convert this structure into something where I can access data in such a way?

Thanks

Juraj Kirchheim

unread,
Aug 19, 2014, 4:48:42 AM8/19/14
to haxe...@googlegroups.com
Uh, what's wrong with `obj.a.b.c.d`? What's the whole point of
building a typed structure, if you're then using dynamic access?

You can always do something like this:

function access(o:Dynamic, path:String):Dynamic {
for (p in path.split('.'))
o = Reflect.field(o, p);
return o;
}
access(obj, 'a.b.c.d');

Best,
Juraj
> --
> To post to this group haxe...@googlegroups.com
> http://groups.google.com/group/haxelang?hl=en
> ---
> You received this message because you are subscribed to the Google Groups
> "Haxe" group.
> For more options, visit https://groups.google.com/d/optout.

Keith McDonald

unread,
Aug 19, 2014, 5:00:52 AM8/19/14
to haxe...@googlegroups.com
Does this mean a typed structure should be used when you know exactly what you are looking for all the time like a.b.c.d.
while a map should be used when there are uncertain components a["b"]["c"]["d"]


I had thought if I had puzzles.puzzle1 and puzzles.puzzle2 I was going to be able to access them like so: puzzles."puzzle1" or puzzles["puzzle1"] because I wasn't certain if I wanted to deal with puzzle1 or puzzle2. Obviously I was wrong.

Good to know though.
Thanks



Juraj Kirchheim

unread,
Aug 19, 2014, 5:32:50 AM8/19/14
to haxe...@googlegroups.com
That's relatively accurate, yes.

However, since it seems you are actually generating the structure at
compile time, I seriously wonder where the element of uncertainty
comes from. Avoid dynamic magic like the plague. It's just a matter of
habit. And it's a habit that greatly pays off in the long run. Trust
me.

You can of course always do something like this: http://try.haxe.org/#6B3f4
That'll allow you to traverse a Map/Object/Array structure just with
`[ ]` access.
But please understand that this is just a very smart way to shoot
yourself in the foot very badly ;)

Best,
Juraj
Reply all
Reply to author
Forward
0 new messages