How can I check the last element when scrolling through a structure in ColdFusion?

I want to iterate over the structure and output something for all elements except the last one. For arrays, this is easy to do by checking if the current index is the last one, although how can this be done for structures?

Sample code:

<cfscript>
myStruct = {
  item1 = "foo",
  item2 = "bar",
  item3 = "baz"
};
</cfscript>

<cfoutput>
<cfloop collection="#myStruct#" item="item">
  #myStruct[item]#
  <!--- Here should be the conditional output --->
</cfloop>
</cfoutput>

      

+3


source to share


2 answers


Just increment your "index" as you loop:

<cfscript>
myStruct = {
  item1 = "foo",
  item2 = "bar",
  item3 = "baz"
};
totalItems = StructCount( myStruct );
thisItemNumber = 1;
</cfscript>

<cfoutput>
<cfloop collection="#myStruct#" item="item">
  #myStruct[item]#
  <cfset thisIsNotTheLastItem = ( thisItemNumber LT totalItems )>
    <cfif thisIsNotTheLastItem>
        is not the last item<br/>
    </cfif>
    <cfset thisItemNumber++>
</cfloop>
</cfoutput>

      



EDIT: here's an alternative using an array

<cfscript>
myStruct = {
  item1 = "foo",
  item2 = "bar",
  item3 = "baz"
};
totalItems = StructCount( myStruct );
keys = StructKeyArray( myStruct );
lastItem = myStruct[ keys[ totalItems ] ];
</cfscript>
<cfoutput>
<cfloop array="#keys#" item="key">
    #myStruct[ key ]#
    <cfif myStruct[ key ] IS NOT lastItem>
        is not the last item<br/>
    </cfif>
</cfloop>
</cfoutput>

      

+3


source


This would be an easy solution.



<cfscript>
    myStruct = {
      item1 = "foo",
      item2 = "bar",
      item3 = "baz"
   };
</cfscript>
<cfset KeyListArray = ListToArray(StructKeyList(myStruct))>
<cfoutput>
    <cfloop from="1" to="#(ArrayLen(KeyListArray)-1)#" index="i"> 
       #myStruct[i]#
      <!--- Here should be the conditional output --->
    </cfloop>
</cfoutput>

      

+1


source







All Articles