With many developers these days writing web applications using popular Javascript libraries (e.g. Prototype or jQuery), many find themselves having to work with data objects in Javascript to enhance the user experience.
In a recent project, I was implementing a screen that required many popup dialog boxes, related Ajax calls, and periodic status updates to ensure a slick interface to the users without the need for any screen refreshes.
Without going into the nitty, gritty of the business reasons behind all the doo-dads I was creating, I reached a point where I needed to take ColdFusion queries and convert them to Javascript objects in order to push data from function to function.
To avoid further confusion, this function is simply a customization of the existing toScript() function available in ColdFusion (you can see I use it in my code below). What this does is allow you to customize the structure of the resulting Javascript object.
ColdFusion query to Javascript object converter
<cfcomponent displayname="QueryToObject" hint="Converts a ColdFusion query into a simple Javascript object" output="false">
<cffunction name="convert" displayname="convert" hint="Converts a query to a Javascript object" access="public" output="true" returntype="void">
<cfargument name="queryName" displayName="queryName" type="Query" hint="The ColdFusion query to be converted" required="true" />
<cfargument name="objectName" displayName="objectName" type="string" hint="The name of the resulting Javascript object" required="true" />
<cfargument name="idColumn" displayName="idColumn" type="string" hint="The unique identifier column of the query to be used in the Javascript object" required="true" />
<cfset var local = structNew() />
<cfset local.jsMappingStruct = StructNew() />
<cfprocessingdirective suppresswhitespace="true">
<script>
<cfloop query="arguments.queryName">
<cfloop from="1" to="#listLen(arguments.queryName.columnList)#" index="local.c">
<cfset local.colName = listGetAt(arguments.queryName.columnList, local.c) />
<cfset local.cell = arguments.queryName[local.colName][arguments.queryName.currentRow] />
<cfif isDate(local.cell)>
<cfset local.cell = dateFormat(local.cell, "mm/dd/yyyy") />
<cfelseif isNumeric(local.cell)>
<cfset local.cell = val(local.cell) />
</cfif>
<cfset local.jsMappingStruct[local.colName] = local.cell />
</cfloop>
#toScript(local.jsMappingStruct,arguments.objectName & arguments.queryName[arguments.idColumn][arguments.queryName.currentRow],true,false)#
</cfloop>
</script>
<cfreturn />
</cfprocessingdirective>
</cffunction>
</cfcomponent>
Making the call
<cfset createObject("component", "utility.data.converters.javascript.QueryToObject").convert(steelers, "steeler.number_", "jerseyNumber") />
The results
<script>
steelers.number_43= new Object();
steelers.number_43["first_name"] = "Troy";
steelers.number_43["last_name"] = "Polamalu";
steelers.number_43["position"] = "Safety";
steelers.number_43["nfl_ranking"] = "1";
</script>
