coldfusioncoldfusion-11lucee

writing a logic to check if value exists


working on the data returned by code

Trying to add some logic that if the value exists, show it else put empty

<cfset myStruct = {
    "access_token" : "#st.access_token#",
    "id": "#res.names[1].metadata.source.id#",
    "name" : "#isDefined('res.names') ? res.names[1].displayname : ''#",
    "other" : {
        "email" : "#res.emailAddresses[1].value#"
    }
}>

Open in new window

its not clean and it throws error on line 3 which is ID, so what kind of isDefined or structkeyexists i can write if it exists add it, else put an empty value


Solution

  • You could try Elvis operator

    Edit: Unless you really need the values as a string, you do not need to use pounds to output the values

    Edit 2: Have updated the example to use the right comment

    <cfset myStruct = {
          "access_token" : "#st.access_token#" <!--- If you have numeric token and need it to be a string --->
        , "id"           : res.names[ 1 ].metadata.source.id ?: ""
        , "name"         : res.names[ 1 ].displayname        ?: ""
        , "other"        : {
            "email" : res.emailAddresses[ 1 ].value ?: ""
        }
    }>