tags:

views:

177

answers:

2

Page 116 of the developer's guide says "Unlike the cfloop tag, CFScript for-in loops do not provide built-in support for looping over queries and lists."

Q: How do I loop over a list using the new script syntax in ColdFusion 9?

<cfloop list="#qry.Columnlist#" index="FieldName">
   <cfset form[FieldName] = qry[FieldName][1]>
</cfloop>
+3  A: 
<cfscript>
  var i = 0;
  var l = ListLen(qry.Columnlist);
  var FieldName = "";
  for (i = 1; i lte l; i = i + 1)  // you also can use i++ instead
  {
    FieldName = ListGetAt(qry.Columnlist, i);
    form[FieldName] = qry[FieldName][1];
  }
</cfscript>
Tomalak
Slightly shorter form: for (i = 1; i <= qry.RecordCount; i++) {}
Sergii
@Sergii: That's the whole point - it's not about the `RecordCount`, but about the length of the `ColumnList`. ;-)
Tomalak
Oh, you're right. Sorry :)
Sergii
Thank you! I'll check this out shortly!
cf_PhillipSenn
+2  A: 

I would turn the list into an array first. ListGetAt() is not efficient to be called n times in a loop. ArrayLen() however should be quite fast.

<cfscript>
arr = ListToArray(qry.Columnlist);

for (i = 1; i <= ArrayLen(arr); i++)
{
    fieldName = arr[i];
    form[FieldName] = qry[FieldName][1];
}
</cfscript>
Henry