CFLib Flatten Struct UDF
Hi today I won lunch by implementing a modified Depth First Tree Traversal on a nested struct to flatten the struct with dot notation keys (There is a pending CFLib submission for this). The main requirement that the existing function on CFLib did not fulfil was that I needed to show the complete path from root node to leaf (or key). The logic for doing this is rather simple (provided you think that recursion is simple!), at each level keep track of the current “path” string that you have already been on and pass it down every time you recurse. Here is the code (fully commented in place of me explaining it elsewhere).
<!--- Flattens nested struct and returns the result. ---> <cffunction name="flattenStruct" returnType="struct"> <cfargument name="original" type="struct" required="true"><!--- struct to flatten ---> <cfargument name="delimiter" required="false" type="string" default="." /> <cfargument name="flattened" type="struct" default="#StructNew()#" required="false"><!--- result struct, returned at the end ---> <cfargument name="prefix_string" type="string" default="" required="false"><!--- used in the processing, stores the preceding struct names in the current branch, ends in a delimeter ---> <!--- get this level's elements ---> <cfset var names = StructKeyArray(original)> <cfloop array="#names#" index="name"> <!--- Test if nested struct or value ---> <cfif IsStruct(original[name])> <!--- if struct append key to prefix and recurse ---> <cfset flattened = recursion(original[name], delimiter, flattened, prefix_string & name & delimiter)> <cfelse> <!--- else add the key and path to the flattened struct ---> <cfset flattened[prefix_string & name] = original[name]> </cfif> </cfloop> <cfreturn flattened> </cffunction>
Note: Will post CFLib link when it is approved.
Edit: Well I only updated something that was already there, so here’s the link and I have updated credits in the code: http://www.cflib.org/udf/flattenStruct