Last active
September 9, 2021 17:27
-
-
Save JamoCA/4fcb3a8c691f29199d23c02941bece11 to your computer and use it in GitHub Desktop.
ColdFusion isStructPathValid() User-Defined Function - Returns true if deeply nested path exists (cfml/java)
This file contains 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
<!--- 20210909 isStructPathValid(struct, name, anyArray) - Returns true if deeply nested path exists (allows array notation) | |
Written to solve this Adobe ColdFusion Community question | |
https://community.adobe.com/t5/coldfusion-discussions/fun-with-isdefined-vs-keyexists/m-p/12368900#M189750 | |
This UDF is Lucee-friendly and array-compatible. It can optionally accept "[]" to match any array position. | |
---> | |
<cfscript> | |
boolean function isStructPathValid(required struct struct, required string name, boolean anyArray=false) output=true hint="Returns true if deeply nested path exists" { | |
local.results = structFindKey(arguments.struct, listLast(arguments.name, "."), "all"); | |
if (not arrayLen(local.results)) return false; | |
for(local.result in local.results){ | |
if (local.result.path is "." & arguments.name) return true; | |
if (arguments.anyArray && local.result.path.replaceAll("\[\d+\]","\[\]") is "." & arguments.name) return true; | |
} | |
return false; | |
} | |
apiResponse = [ | |
"data": [ | |
"errors": [ | |
"surname is invalid", | |
{"errorCode": 1} | |
], | |
"nullTest": javacast("null", 0) | |
] | |
]; | |
</cfscript> | |
<cfdump var="#apiResponse#" label="Sample object (with null item)"> | |
<cfoutput> | |
<h2>isStructPathValid( apiResponse, "data.errors" )</h2> | |
#isStructPathValid( apiResponse, "data.errors" )# | |
<h2>isStructPathValid( apiResponse, "data.nullTest" )</h2> | |
#isStructPathValid( apiResponse, "data.nullTest" )# | |
<h2>isStructPathValid( apiResponse, "data.does_not_exist" )</h2> | |
#isStructPathValid( apiResponse, "data.does_not_exist" )# | |
<h2>isStructPathValid( apiResponse, "data.errors[2].errorcode" )</h2> | |
#isStructPathValid(apiResponse, "data.errors[2].errorcode" )# | |
<h2>isStructPathValid( apiResponse, "data.errors[].errorcode", true )</h2> | |
#isStructPathValid(apiResponse, "data.errors[].errorcode", true )# | |
</cfoutput> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment