COMMUNITY

Using inline vars in objects as keys

anon-structure

(Jon Grant) #1

I have and object with a series of value pairs:

var pairsOBJ = {
“name”:“value”,
}

I would rather have:

public static inline var NAME:String = “name”;

var pairsOBJ = {
NAME:“0”
}

Problem is when I read the field, the field name is NAME rather than “name”. Is there a way to make the inline var string show up instead?


(Louis Pearson) #2

I don’t believe this is something that you can do without a macro. What is it that you are looking to do? If you just want to be able to access object fields at runtime, use the reflection API.


(Dan Korostelev) #3

Looks like you’re looking for haxe.DynamicAccess


(Asim) #4

what i got from your question :

try this :

class Test {
 
    static function main() {
        trace("Haxe is great!");
		
        var pairsOBJ = { "NAME":"value" };
        
        var DATA:DataModal;
        DATA = pairsOBJ;
        
        trace(DATA.NAME);
    }
}

typedef DataModal=
{
  	var NAME:String;
}

https://try.haxe.org/#45eF3


(Juraj Kirchheim) #5

You may want to use a Map instead of an object here.

var pairs = [
  NAME => "0"
];

If you really need it to be an object, then it’ll only work with a macro.


#6

I know it’s outdated but found this looking for similiar problem.
Going JS way (and Dan’s suggestion) it could be sth like:

    public static inline function NAME() { return "name"; }

    static function main() {
        var pairsOBJ:haxe.DynamicAccess<Dynamic> = {};
        pairsOBJ.set(NAME(), "value");
        trace(pairsOBJ[NAME()]);
	trace(pairsOBJ.exists("name")); // true        
    }

Unfortunately it seems you can’t use (even static/derived/calculated) expression neither inlined function result directly as field identifier during object declaration [w/o macros] - it could be nice if possible.