Created
July 18, 2025 18:16
-
-
Save DeveloperOfficeCom/ab67b8cda0e528d3a670e836eca8b1ab to your computer and use it in GitHub Desktop.
Get struct value with default fallback
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!--- | |
GET Function | |
Description: Safely retrieves a value from a struct with a default fallback. Returns the value if the key exists, otherwise returns the default value without throwing an error. | |
Parameters: | |
- struct: The struct to retrieve value from (required) | |
- key: The key to look up (required) | |
- defaultValue: Value to return if key doesn't exist (optional, default: "") | |
Returns: The value from the struct if key exists, otherwise the default value | |
Usage: | |
<cfset result = get(myStruct, "name", "Unknown")> | |
<cfset result = get(userSettings, "theme", "light")> | |
<cfset result = get(config, "timeout", 30)> | |
Examples: | |
get({name:"John"}, "name", "Unknown") returns "John" | |
get({name:"John"}, "age", 0) returns 0 | |
get({}, "anything", "default") returns "default" | |
get({foo:""}, "foo", "default") returns "" | |
Author: DeveloperOffice.com | |
Language: ColdFusion/Lucee | |
License: MIT (https://opensource.org/licenses/MIT) | |
Version: 1.0 | |
---> | |
<cffunction name="get" returntype="any" output="false"> | |
<cfargument name="struct" type="struct" required="true"> | |
<cfargument name="key" type="string" required="true"> | |
<cfargument name="defaultValue" type="any" required="false" default=""> | |
<!--- Check if key exists in struct ---> | |
<cfif structKeyExists(arguments.struct, arguments.key)> | |
<!--- Check if value is null ---> | |
<cftry> | |
<cfset var value = arguments.struct[arguments.key]> | |
<cfif NOT isNull(value)> | |
<cfreturn value> | |
<cfelse> | |
<cfreturn javaCast("null", "")> | |
</cfif> | |
<cfcatch> | |
<!--- If accessing causes error, return the value anyway ---> | |
<cfreturn arguments.struct[arguments.key]> | |
</cfcatch> | |
</cftry> | |
<cfelse> | |
<cfreturn arguments.defaultValue> | |
</cfif> | |
</cffunction> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment