Working With Each Key In A Struct

Earlier today I saw a tweet from Marc Esher where he was looking to do something like: mystruct.each( myFunctionThatDoesStuffWithEachKeyItVisits). While you can't get that exact syntax, you can run a function on each key pretty easily. Below is an example:

<cffunction name="StructEach" returntype="Array">
   <cfargument name="struct" type="struct" required="true">
   <cfargument name="func" type="any" requried="true">   
   <cfset var results = [] />   
   <cfloop collection="#arguments.struct#" item="key">   
      <cfset ArrayAppend(results,arguments.func(arguments.struct[key])) />
   <cfreturn results />   

<cffunction name="FindIt" returntype="boolean">
   <cfargument name="item" type="string" required="true">   
   <cfreturn REFindNoCase('not a test$',arguments.item) />

myStruct = {};
myStruct.key1 = "This is a test.";
myStruct.key2 = "This is a test";
myStruct.key3 = "This is not a test.";
myStruct.key4 = "This is not a test";
myStruct.key5 = "Not a test, this is.";
results = StructEach(myStruct,FindIt);

<cfdump var="#results#" />

Not sure if it is exactly what Marc was looking for, but cool none the less.

Adam Cameron's Gravatar Nice work.

One thing that occurs to me, in passing back an ARRAY, you actually lose the mapping between which struct key corresponds to which array element, because struct keys are intrinsically - and by design - unordered.

I'd recommend passing back another struct, keying it the same as the original, with the value being the result of the call to the passed-in function (if that makes sense).

result[key] = arguments.func(arguments.struct[key]))

# Posted By Adam Cameron | 7/8/09 10:29 AM
Nathan Mische's Gravatar Good point Adam. Using an array would also be problematic if you wanted to make this function recursive, as arrays are passed by value in CF.

I put this together quickly, mainly to show that you can pass a function to as an argument to another function.
# Posted By Nathan Mische | 7/8/09 10:44 AM
BlogCFC was created by Raymond Camden. This blog is running version 5.8.001.