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)>
			<!--- else add the key and path to the flattened struct --->
			<cfset flattened[prefix_string & name] = original[name]>

	<cfreturn flattened>

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:

About Simeon Cheeseman

I enjoy a wide variety of computer and board games, have a BSc in Computer Science and have played percussion for 18 years.

Posted on September 1, 2011, in ColdFusion. Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: