Displaying Structure Information in Coldfusion
I want to show the value of a structural key, for example:
#stReviewDetail['tags']['travelParty']['value']#
It is possible that tags
, travelParty
or is value
missing. What's the best way to check if the structure hierarchy is available? Something like:
<cfif StructKeyExists(stReviewDetail, 'tags') AND
StructKeyExists(stReviewDetail['tags'], 'travelParty') AND
StructKeyExists(stReviewDetail['tags']['travelParty'], 'value') >
....
</cfif>
or is there a better way to do this?
+1
source to share
2 answers
Several StructKeyExists are ugly and it's easy to write a function to simplify this:
Application:
<cfif CheckNestedKeys(stReviewDetail,['tags','travelParty','value']) >
#stReviewDetail['tags']['travelParty']['value']#
</cfif>
Code:
<cffunction name="CheckNestedKeys" returntype="Boolean" output=false>
<cfargument name="Struct" type="Struct" required />
<cfargument name="Keys" type="Array" required />
<cfset var CurStruct = Arguments.Struct />
<cfloop index="local.CurKey" array=#Arguments.Keys# >
<cfif StructKeyExists(CurStruct,CurKey)>
<cfset CurStruct = CurStruct[CurKey] />
<cfelse>
<cfreturn false />
</cfif>
</cfloop>
<cfreturn true />
</cffunction>
+5
source to share