Skip to content

Instantly share code, notes, and snippets.

@iknowkungfoo
Last active January 4, 2018 05:33
Show Gist options
  • Save iknowkungfoo/b4a20412e8718106d51f26bb4da41edf to your computer and use it in GitHub Desktop.
Save iknowkungfoo/b4a20412e8718106d51f26bb4da41edf to your computer and use it in GitHub Desktop.
Evolution of creating an array of structs from a ColdFusion query.

While updating my cfquery-to-json repoistory to use the latest ColdFusiuon 2016 functions, I was amazed at how much less code it takes to return the same data structures.

ColdFusion 9+

/**
* Convert n query object to an array of structs.
* @param required query data Query Object
* @return array
*/
public array function arrayOfStructs( required query data ) {
    var results = [];
    var temp = {};
    var q = arguments.data;
    var rc = q.recordCount;
    var fields = listToArray(arguments.data.getColumnNames());
    var fc = arrayLen(fields);
    var x = 0;
    var y = 0;
    var fieldName = "";

    for ( x = 1; x LTE rc; x++ ){
        temp = {};
        for ( y = 1; y LTE fc; y++ ) {
            fieldName = fields[y];
            temp[fieldName] = q[fieldName][x];
        }
        arrayAppend( results, temp );
    }
    return results;
}

ColdFusion 10+

public array function arrayOfStructs(required query data) {
    var results = [];
    var record = {};
    var columns = arguments.data.getColumnNames();
    for (var x in arguments.data) {
        record = {};
        for (var y in columns) {
            record[y] = x[y];
        }
        arrayAppend(results, record);
    }
    return results;
}

ColdFusion 2016+

The query member function each() references the contents of each row as a struct.

public array function arrayOfStructs(required query data, boolean lowerCase = false) {
    var results = [];
    arguments.data.each(function(row) {
        arrayAppend(results, arguments.row);
    });
    return results;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment