Utility Functions: StructToListPairs() and ListPairsToStruct()

Today we have a pair of functions designed to convert structures into list pairs and back again. They serve as the back bone of another pair of functions that I'll release soon. StructToListPairs() is also useful when constructing long links (such as creating "sort" links for tables).

<cffunction name="StructToListPairs" returntype="string">
    <cfargument name="struct" type="struct" requried="true" />
    <cfargument name="delimiter1" type="string" required="false" default="&" />
    <cfargument name="delimiter2" type="string" required="false" default="=" />
    
    <cfset var buffer = CreateObject("java", "java.lang.StringBuffer").init() />
    
    <cfloop collection="#arguments.struct#" item="key">
        <cfset buffer.append(key) />
        <cfset buffer.append(delimiter2) />
        <cfset buffer.append(arguments.struct[key]) />
        <cfset buffer.append(delimiter1) />
    </cfloop>
    
    <cfif buffer.length() gt 1>
        <cfset buffer.setLength(buffer.length()-1) />
    </cfif>
    
    <cfreturn buffer.toString() />
</cffunction>

<cffunction name="ListPairsToStruct" returntype="struct">
    <cfargument name="list" type="string" requried="true" />
    <cfargument name="delimiter1" type="string" required="false" default="&" />
    <cfargument name="delimiter2" type="string" required="false" default="=" />
    
    <cfset var returnValue = StructNew() />
    
    <cfloop list="#arguments.list#" index="pair" delimiters="#arguments.delimiter1#">
        <cfset returnValue[ListFirst(pair, arguments.delimiter2)] = ListLast(pair, arguments.delimiter2) />
    </cfloop>
    
    <cfreturn returnValue />
</cffunction>

 

Comments

Jon Hartmann, July 2011

I'm Jon Hartmann and I'm a C# .Net developer by day, a ColdFusion guru by night, and all around Javascript fanatic. Stay right here to read my technical posts as I grapple with mysterious error messages, user interface design questions, and all things baffling and irksome about programming for the web. Learn more about me.

Post a job. Find one. authenticjobs.com

Interested in becoming a sponsor? Contact me.