Utility Function: StructExtract()

Working with ArgumentCollections reminded me that I sometimes wish that I had an easy way to pull out just a few values from a structure into a new structure. So I wrote one:


<cffunction name="StructExtract" output="false" returntype="struct">
    <cfargument name="struct" type="struct" required="true"/>
    <cfargument name="keyList" type="string" required="true"/>

    <cfset var returnStruct = StructNew() />

    <cfloop list="#UCase(arguments.keyList)#" index="key">
        <cfset returnStruct[key] = arguments.struct[key] />
    </cfloop>

    <cfreturn returnStruct />
</cffunction>

Example


<cfset struct1 = {
Naomi = "Sweet",
Kit = "Tough",
Christina = "Cocky"
} /
>


<cfdump var="#struct1#" labe="struct1"/>

<cfset struct2 = StructExtract(struct1, "naomi,kit") />

<cfdump var="#struct2#" labe="struct2"/>

 

Comments

Jon Hartmann, July 2011

I'm Jon Hartmann and I'm a Javascript fanatic, UX/UI evangelist and former ColdFusion master. I blog about 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.