Search code examples
coldfusionstructuremodulus

coldfusion less cumbersome way to create four structures based on array modulus


I have an array "varray" which needs to be split into four structures. The first of each four elements should be in structure 1, the second in structure 2, etc. I have some working code to do this, but it feels to me like there should be a less cumbersome way. Here is the code:

<cfset xord  = StructNew()>
<cfset xsort = StructNew()>
<cfset xsel  = StructNew()>
<cfset xmer  = StructNew()>

<cfloop from = '1' to = "#ArrayLen(varray)#" index = 'i'>
  <cfset fieldname = farray[i]> <!---farray previously defined --->
  <cfset val = varray[i]> <!---varray previously defined --->
 <cfset j = i%4>

 <cfif j EQ 1>
   <cfset xord[fieldname] = val>
 <cfselseif j EQ 2>
   <cfset xsort[fieldname]= val>
 <cfelseif j EQ 3>
   <cfset xsel[fieldname] = val>
 <cfelseif j EQ 0>
   <cfset xmer[fieldname] = val>
 </cfif>

</cfloop>  

Can anyone suggest a better way to do this?


Solution

  • (You didn't mention your version, so I don't know if you have access to newer functions like array each(). Keep in mind there's slicker options in newer versions)

    Instead of creating separate variables, create a single structure containing the 4 variables, and an array of names. Then use the array and MOD to populate the substructures. Note, the example below creates the subsubstructures up front to ensure they always exist - even if the field/value arrays are empty or contain less than 4 elements.

    TryCF.com Example

    <cfset farray = ["A","B","C","D","E","F","G","Q","T"]>
    <cfset varray = ["11","22","33","RR","55","NN","77","68","46"]>
    <cfset data   = {xOrd={},xSort={},xSel={},xMer={}}>
    <cfset names  = ["xOrd","xSort","xSel","xMer"]>
    
    <cfloop from="1" to="#ArrayLen(varray)#" index="i">
      <cfset fieldName = farray[i]>
      <cfset fieldValue = varray[i]> 
      <cfset structName = names[i%4+1]>
      <cfset data[structName][fieldName] = fieldValue>
    </cfloop>  
    

    The substructures can be accessed through the parent, data.

    <cfdump var="#data.xOrd#" label="data.xOrd">
    <cfdump var="#data.xSort#" label="data.xSort">
    <cfdump var="#data.xSel#" label="data.xSel">
    <cfdump var="#data.xMer#" label="data.xMer">