Copy link to clipboard
Copied
Hello,
I was curious if it was possible to dynamically create an implicit structure where you might occasionally want to omit some keys from being added to the structure?
I played around with using ternary operators in the structure creation with no luck.
<cfset temp = {
name = "Dave",
(1 IS 1 ? "" : Job = "Superhero")
} />
The only way I can see doing this now would be to create the structure and then use StructKeyDelete on the keys I want to remove OR build structures the traditional way and cfif my way around the keys I don't want to add."
Ex: <cfset structKeyDelete(temp,"Job") />
or
<cfset temp = structNew() />
<cfset temp.name = "Dave" />
<cfif 1 NEQ 1>
<cfset temp.job = "Superhero" />
</cfif>
Does anyone know how to create dynamic keys in a structure while defining it implicitly?
Thanks!
I can think of at least one reason why this fails. If there is just one key-value pair, there will be a comma stranded at the end.
You can of course tinker dynamically with the content of the keys of a struct and their respective values. However, a struct is an object, with set characteristics such as number of key-value pairs. So, it would be difficult to dynamically change the number of key-value pairs 'from within' the struct. Even if what you are trying to do were possible, it would be more c
...Copy link to clipboard
Copied
I can think of at least one reason why this fails. If there is just one key-value pair, there will be a comma stranded at the end.
You can of course tinker dynamically with the content of the keys of a struct and their respective values. However, a struct is an object, with set characteristics such as number of key-value pairs. So, it would be difficult to dynamically change the number of key-value pairs 'from within' the struct. Even if what you are trying to do were possible, it would be more complex, and would certainly involve more code, than the ordinary alternative you mention.
In any case, here is a version of your original idea that works:
<cfset temp = (1 IS 2 ? {name="Dave"} : {name="Dave",Job="Superhero"})>
<cfdump var="#temp#">
Copy link to clipboard
Copied
Thanks BKBK. Yeah I saw the comma issue after I submitted the example. However you are totally right that the amount of code needed to make the structure in this way would be way more than just removing the unwanted fields after the fact. Thank you for the assistance.