Hi Everyone, is there a better way - other than u...
# cfml-general
g
Hi Everyone, is there a better way - other than using evaluate(), to name a variable, with a dynamic portion?
Copy code
<cfscript>
	myArray = ["myObj1", "myObj2", "myObj3"];

	myResultsArray = [];

	loop item="item" index="i" array=myArray {

		"myStruct#i#" = {};

		// run some function here for result Z. "item.someFunction()"
		z = "myVal_I_got_back";

		structInsert(evaluate("myStruct#i#"), "theZ", "#z#");
		structInsert(evaluate("myStruct#i#"), "someOtherStuff", "MoreStuff");

		arrayAppend(myResultsArray, evaluate("myStruct#i#"));
	}

	dump(myResultsArray);
</cfscript>
It works - but I would like to avoid
evaluate()
, if I can. Instead of
structInsert()
I tried
myStruct#i#.theZ =
myStruct#i#[thez] =
myStruct#i#["theZ"] =
myStruct#i#.[theZ] =
mystruct#i#.["theZ"] =
and also tried all of those again but quoting the start;
"myStruct#i#".theZ =
"myStruct#i#"[theZ] =
"mystruct#i#"...
And it kept complaining about using the "#" in the name portion... Thanks.
m
yes scope["mystruct" & i]
👍🏼 1
Each of the scopes can act as a Struct... So your code with those changes: https://trycf.com/gist/c5db3ea8354ba3f07678767d105a1153/lucee5?theme=monokai
👍🏼 1
g
@Michael Schmidt or just direct assignment;
variables["myStruct" & i]["theZ"] = "#z#";
nonetheless - Thanks very much - for putting me straight!
👆 1
m
just for cleanliness i would even avoid the "#z#" and just say z
👍🏼 1
👍 1
a
You can also do this (which is handy if you have several dynamic parts to your key)
Copy code
variables["myStruct#i#"]["theZ"] = z;
👍🏼 1
m
so one thing i do since most likely you are reusing that same string multiple times is I create a string first let's
Copy code
myReference="myStruct" & i; // or myReference="myStruct#i#";

and then variables[myReference]["theZ"] = z
👍🏼 1
👍 2
g
I keep forgetting that CFML has some Functional Programming support, like
.each()
Thanks!