arraysjsoncoldfusioncfloop

How to access nested array


enter image description here

I am trying to access recipeIngredient in this array.

I have tried this:

<cfloop from="1" to="#ArrayLen(contents)#" index="i">
<cfoutput>
 #i.recipeIngredient#<br>
</cfoutput>
</cfloop>

I am getting an error "You have attempted to dereference a scalar variable of type class coldfusion.runtime.Array as a structure with members."


Solution

  • You are using nested data, so you need to check for the existance of that particular struct that has the key recipeIngredient to output it.

    In that case I wouldn't iterate the arrays by index, because CFML gives the wonderful possibilty to cfloop an array by using the attribute array and iterate it by its items, which feels more natural and easier to read.

    Also, don't add <cfoutput> to the inner body of loops, because it adds more overhead to your cfengine. Instead, embrace the loops with cfoutput.

    <cfoutput>
       <cfloop array="#contents#" item="item">
          <cfif isStruct( item ) and structKeyExists( item, "recipeIngredient")>
             <cfloop array="#item.recipeIngredient#" item="ingredient">
                #ingredient#<br>
             </cfloop>
          </cfif>
    
          <!--- for looping over a struct like recipeinstructions use collection attribute--->
          <cfif isStruct( item ) and structKeyExists( item, "recipeinstructions")>
             <cfloop collection="#item.recipeinstructions#" item="key">
               Value for key '#encodeForHTML(key)#': #encodeForHTML( item.recipeinstructions[key])#<br>
             </cfloop>
          </cfif>
    
       </cfloop>
    </cfoutput>