Search code examples
coldfusioncoldfusion-9cfml

Any better way to loop through a collection (struct) in CFML?


Please have a look at the code block below:

<cfset index = 0 />
<cfloop collection="#anotherPerson#" item="key" >
    <cfset index = index+1 />
    <cfoutput> 
         #key# : #anotherPerson[key]# 
         <cfif index lt ArrayLen(structKeyArray(anotherPerson))> , </cfif>
    </cfoutput>
</cfloop>

<!--- Result 

   age : 24 , haar : Blondes haar , sex : female , ort : Hanau

---->

Now can you please tell me how could I achieve the same result without setting an index outside and incrementing it inside the loop? If you notice carefully, I had to write two more cfset tag and one cfif tag with expensive code just to avoid a comma (,) at the end of the collection!


Solution

  • Some friends provided two different solutions. Both are efficient and elegant!

    Solution 1

    <cfset isFirst = true />
    <cfloop collection="#anotherPerson#" item="key" >
        <cfif isFirst>
            <cfset isFirst = false />
        <cfelse> 
            ,   
        </cfif> 
        <cfoutput> 
           #key# : #anotherPerson[key]# 
        </cfoutput>
    </cfloop>
    

    Solution 2

    <cfset resultList = "" />
    <cfloop collection="#anotherPerson#" item="key" >
        <cfset resultList = ListAppend(resultList, "#key# : #anotherPerson[key]#" ) />
    </cfloop>
    

    Cheers!