Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A ColdFusion UDF to convert a query to a struct, or an array of structs.
<cffunction name="QueryToStruct" returntype="any" hint="Converts a query to a struct, or an array of structs">
<cfargument name="query" type="query" required="true"/>
<cfargument name="row" type="query"/>
<cfargument name="forceArray" type="boolean" default="false"/>
<cfscript>
var local = StructNew();
var result = StructNew();
var idx = "";
var colName = "";
var columnLabels = arguments.query.getMetaData().getColumnLabels();
</cfscript>
<cfif isDefined("arguments.row")>
<cfset local.row = arguments.row/>
<cfelseif arguments.query.recordCount eq 1>
<cfset local.row = 1/>
</cfif>
<cfif isDefined("local.row") and not arguments.forceArray>
<cfloop array="#columnLabels#" index="colName">
<cfset StructInsert(result, colName, arguments.query[colName][local.row])/>
</cfloop>
<cfelseif isDefined("local.row")>
<cfset result = ArrayNew(1)/>
<cfset ArrayAppend(result, StructNew())/>
<cfloop array="#columnLabels#" index="colName">
<cfset StructInsert(result[1], colName, arguments.query[colName][local.row])/>
</cfloop>
<cfelse>
<cfset result = ArrayNew(1)/>
<cfloop from="1" to="#arguments.query.recordCount#" index="idx">
<cfset local.tempStruct = StructNew()/>
<cfloop array="#columnLabels#" index="colName">
<cfset StructInsert(local.tempStruct, colName, arguments.query[colName][idx])/>
</cfloop>
<cfset ArrayAppend(result, local.tempStruct)/>
</cfloop>
</cfif>
<cfreturn result/>
</cffunction>
@bean5

This comment has been minimized.

Copy link

@bean5 bean5 commented Jan 30, 2014

How does this compare in terms of functionality with the methodology available at http://www.bennadel.com/blog/149-Ask-Ben-Converting-A-Query-To-A-Struct.htm ?

@higgjose

This comment has been minimized.

Copy link

@higgjose higgjose commented May 1, 2014

I was using Ben's but it set the column names to uppercase. I need to preserve case for Javascript. This one appears to be broken as of today's date.

@charlesr1971

This comment has been minimized.

Copy link

@charlesr1971 charlesr1971 commented Nov 12, 2015

Actually, Coldfusion changes the column names to upper case. You could add a column map argument:

<cfset columnLabels = ArrayToList(arguments.query.getMetaData().getColumnLabels())>
<cfset local.temp = columnLabels>
<cfloop list="#arguments.columnmap#" index="columnamepreservecase">
    <cfset local.temp = ReplaceNoCase(local.temp,columnamepreservecase,columnamepreservecase,"ALL")>
</cfloop>
<cfif ListLen(local.temp)>
    <cfset columnLabels = ListToArray(local.temp)>
</cfif>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment