Search code examples
structcoldfusionlucee

trying to wrap a structure with another set of structure


I am trying to wrap a structure with another structure, but definitely i am missing something

i want to show it like this

account: {
    "name": "Example Account",
    "details": "https://www.example.com"
  }

i am trying this function, but i am missing something, probably i should use structmap, not sure

<cffunction name="SO">
    <cfargument name="name" required="true" type="struct">
    <cfargument name="data" required="true" type="struct">
    <cfloop collection="#arguments.Data#" index="i">
        <cfset arguments.Name['#lcase(i)#'] = arguments.Data[i]>
    </cfloop>   
    <cfreturn arguments.Name>
</cffunction>

Solution

  • When I first looked at this, I thought you essentially wanted to have a new struct with a "name" (containing a string) and a "data" containing a struct.

    Your initial setup is essentially

    <cfset name = "Test" >
    <cfset data = { details: "detail1" , details2: "detail2" } >
    

    When dealing with most data structures in CF, I usually find it much easier and cleaner to work with CFSCRIPT instead of tags. So I came up with

    <cfscript>
        function SO ( required String name, required Struct data ) {
            var retval = { name:"",data:{} } ;
    
            retval.name = arguments.name ;
    
            arguments.data.map( function(key, val) {
                retval.data[key.lcase()] = val ;
            } ) ;
    
            return retval;
        }
    
        writedump( SO(name,data) ) ;
    </cfscript>
    

    Trying to unwind this, it appears that all you're trying to do is add a "name" value to your "data" struct. This can easily be done with

    <cffunction name="SO_tags">
        <cfargument name="name" required="true" type="string">
        <cfargument name="data" required="true" type="struct">
    
        <cfset retval2 = arguments.data >
        <cfset retval2.name = arguments.name>
        <cfreturn retval2>
    </cffunction>
    
    <cfset structure = {"account":SO_tags(name,data)}>
    <cfdump var = #structure#>
    

    Or using script, it can come down to just a single line.

    <cfscript>
        function SO3 ( required String name, required Struct data ) {
            return arguments.data.append( {"name":arguments.name} ) ;
        }
    
    writedump( {"account":SO3(name,data)} ) ;
    </cfscript>
    

    Depending on how this fits into the rest of your code, you may not even need a function.

    https://cffiddle.org/app/file?filepath=b6e92a83-ebc9-40eb-a712-f402d7f9ed85/f4fb9f8e-3b60-4a64-8c02-2cd106736df0/4e00abae-b949-4934-86e8-870745259127.cfm

    EDIT: Changed output to nest it within an "account" structure.