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;
}

Search CFLib.org


Latest Additions

Raymond Camden added
QueryDeleteRows
November 04, 2017

Leigh added
nullPad
May 11, 2016

Raymond Camden added
stripHTML
May 10, 2016

Kevin Cotton added
date2ExcelDate
May 05, 2016

Raymond Camden added
CapFirst
April 25, 2016

Created by Raymond Camden / Design by Justin Johnson