Peter
Peter

Reputation: 11920

How to return a list of objects from a cfscript function

I am getting used to ColdFusion. It appears cfscript makes a developer's life easier.

In my cfscript function, I need to:

  1. Run a query "SELECT A, B from MyTable"
  2. For each row of this query, create a new component on the fly that has three properties A, B, and C. Here, C is computed within the function.
  3. Return an array of the new components.

Here is the pseudo-code:

<cfquery name="myq" datasource="mydsn">
    SELECT A, B
   FROM MyTable
</cfquery>

<cfscript>
function MyFunc() {
   // Do the magic and return the array
} 
</cfscript>

I am guessing I would use this function as I would use a query:

<cfset myarray=MyFunc() />
<cfloop index="i" from="1" to="#arrayLen(myarray)#">
   #myarray.A# <br />
   #myarray.B# <br />
   #myarray.C# <br />
</cfloop>

I would appreciate it if you can suggest me how I can accomplish this. I have been searching through Adobe documentation but haven't found a good example that I can relate to. Thank you in advance for your help.

Upvotes: 2

Views: 1455

Answers (2)

James A Mohler
James A Mohler

Reputation: 11120

You probably want something like

 <cfoutput>
 <cfloop index="i" from="1" to="#arrayLen(myarray)#">
  #myarray.A[i]# <br />
  #myarray.B[i]# <br />
  #myarray.C[i]# <br />
 </cfloop>
 </cfoutput>

Overall you should consider returning a query rather than an array

<cfscript>
  query function MyFunc() {
  // Do the magic and return the array
  } 
</cfscript>

Then process it by

 <cfset myQuery = MyFunc()>

 <cfoutput query="myQuery">
      #A# <br />
      #B# <br />
      #C# <br />
 </cfoutput>

One rule of thumb in ColdFusion is: Queries are more powerful than arrays of structs. You can process them that way, but you will miss out on some very power features such as having <cfoutput> iterating over a query.

Upvotes: 1

Henry
Henry

Reputation: 32915

I know I'm not suppose to just paste the link, but it's really all you need.

Then just use new xxx() for new object, ArrayAppend() for constructing an array and return it.

Good luck, let us know if you run into any other problems.

Upvotes: 2

Related Questions