CFLib.org – Common Function Library Project

ArrayOfStructsToStructOfArrays(ar)

Last updated September 21, 2004

author

Nathan Strutz

Version: 1 | Requires: CF5 | Library: DataManipulationLib

Description:
For those times when you're working with complex structures and arrays, here's a function that will rearrange your data. This changes a given array of structures to a structure of arrays.

Return Values:
Returns a struct.

Example:

<cfscript>

ar = arrayNew(1);
ar[1] = structNew();
ar[1].name = 'nathan';
ar[1].date = '1/1/2004';

ar[2] = structNew();
ar[2].name = 'zorro';
ar[2].date = '2/3/2000';

ar[3] = structNew();
ar[3].name = 'lone ranger';
ar[3].date = '4/8/2003';

</cfscript>

<cfdump var="#ar#" label="Array Of Structs">
<cfdump var="#ArrayOfStructsToStructOfArrays(ar)#" label="Struct Of Arrays">

Parameters:

Name Description Required
ar Array of structs. Yes

Full UDF Source:

/**
 * Changes a given array of structures to a structure of arrays.
 * 
 * @param ar 	 Array of structs. (Required)
 * @return Returns a struct. 
 * @author Nathan Strutz (mrnate@hotmail.com) 
 * @version 1, September 21, 2004 
 */
function arrayOfStructsToStructOfArrays(ar) {
	var st = structNew();
	var arKeys = structKeyArray(ar[1]);
	var i=0;
	var j=0;
	var arLen = arrayLen(ar);
	for (i=1;i lte arrayLen(arKeys);i=i+1) {
		st[arKeys[i]] = arrayNew(1);
		for (j=1;j lte arLen;j=j+1) {
			st[arKeys[i]][j] = ar[j][arKeys[i]];
		}
	}
	return st;
}
blog comments powered by Disqus

Search CFLib.org


Latest Additions

Kevin Cotton added
date2ExcelDate
May 5, 2016

Raymond Camden added
CapFirst
April 25, 2016

Chris Wigginton added
loremIpsum
January 18, 2016

Gary Stanton added
calculateArrival...
November 19, 2015

Sebastiaan Naafs - van Dijk added
getDaysInQuarter
November 13, 2015

Created by Raymond Camden / Design by Justin Johnson