Skip to main content
Ben Nadel at Node.js Training with Nodejitsu (Apr. 2011) with: Paolo Fragomeni and Charlie Robbins and Marak Squires
Ben Nadel at Node.js Training with Nodejitsu (Apr. 2011) with: Paolo Fragomeni Charlie Robbins Marak Squires

Reshaping A Struct In ColdFusion

By
Published in — Comments (3)

I've been working on a rendering algorithm for ColdFusion data structures; and part of what makes the algorithm special is that I get to apply my opinionated feelings about the order or keys. For context, I'm sure that most ColdFusion developers have encountered the scenario where you dump-out an error object only to find that the type attribute is rendered last. And every fiber in your being tells you that type should be rendered first. Because you're not a psycho. Because key-order matters. To help me with my algorithm, I've been playing around with a User Defined Function (UDF) called structReshape(); which takes a struct and converts it into an ordered struct using a specified key order.

Essentially, you can give the structReshape() function an array of keys to prioritize within the ordered struct. The function will add those keys first in the specified order. Then, it will append any remaining keys in the secondary sort order.

In the following demo, we'll compare the native dump to the reshaped dump:

<cfscript>

	data = {
		a: "1st",
		AA: "2nd",
		m: "3rd",
		MM: "4th",
		n: nullValue(),
		NN: nullValue(),
		ZZ: "7th",
		z: "8th",
		p: "9th",
	};

	writeDump(
		label = "Native Dump",
		var = data
	);

	reshaped = structReshape(
		data,
		[ "a", "z" ]   // Always list these keys FIRST, in the specified order.
		// , "textnocase" // List remainder keys SECOND, using this sort algorithm.
		// , "asc"
		// , true
		// , true
	);

	writeDump(
		label = "Reshaped Dump",
		var = reshaped
	);

	// ------------------------------------------------------------------------------- //
	// ------------------------------------------------------------------------------- //

	/**
	* I reshape the given struct, returning a new ordered struct with sorted keys. The
	* explicitly supplied keys will be appended to the struct in the specified order. Any
	* remaining keys will be appended to the struct in the sort order.
	*/
	private struct function structReshape(
		required struct source,
		required array keys,
		string sortType = "default",
		string sortOrder = "asc",
		boolean localeSensitive = true,
		boolean excludeNulls = false
		) {

		var result = [:];
		var sortedKeys = source.keyArray();

		if ( sortType != "default" ) {

			sortedKeys.sort( sortType, sortOrder, localeSensitive );

		}

		var allKeys = []
			// First, we'll insert the priority keys in priority order.
			.append( keys, true )
			// Second, we'll insert the remaining keys in sort order.
			.append( sortedKeys, true )
		;

		for ( var key in allKeys ) {

			if ( excludeNulls && ! source.keyExists( key ) ) {

				continue;

			}

			// Note: we're not bothering to see if the given key already exists since
			// re-assigning it won't change the key order. If the key already exists, this
			// is basically a no-op; and keeps things simple.
			result[ key ] = source?[ key ];

		}

		return result;

	}


	/**
	* I return a NULL value. Used primarily to avoid null-reference errors.
	*/
	private void function nullValue() {
		// ... polyfill for Lucee's function.
	}

</cfscript>

Note that I'm explicitly prioritizing ["a","z"] in my reshaped structure. These two keys should always be first. And, when we run this CFML code in Adobe ColdFusion 2025, we get the following output:

Screenshot of native CFDump next to reshaped CFDump.

As you can see, the ["a","z"] keys are listed first in my reshaped struct. The remainder of the keys are listed second. In this case, the remaining keys are sorted in whatever order the .keyArray() iterator naturally returned. I could, however, override that order with the sortType and sortOrder arguments.

Want to use code from this post? Check out the license.

Reader Comments

16,342 Comments

Just as a side-note, in the demo, I use source.keyArray(). However, in reality, since I'm passing some non-native structs into this - such as the ColdFusion error object - I actually use structKeyArray(source) in my implementation. This way, it works with native structs as well as non-native "struct like" objects.

The same is true for source.keyExists() and structKeyExists().

This one of the perpetual problems points of friction with ColdFusion - member methods aren't always available on objects that look, feel, and taste like native CFML data structures. If you defined it, you know what it is; but if it's passed to you by another context (ie, another layer in the stack, another developer), you have to take special care with your assumptions.

1 Comments

Commenting just because I haven't seen ColdFusion mentioned in a really long while. What made you stick with it over the years? I used to be a flash developer (action script was my thing and this looks similar) and I'm interested to see if you remember or were a part of the MXNA community. If you do checkout dxna.dev where I'm trying to revive that dynamic (that's how I found this post).

16,342 Comments

@Akeem,

I've just always enjoyed ColdFusion. It's certainly not a perfect language; but I found that's made enough of the "right" trade-offs to keep programming fun and easy. I've just yet to see another language that looks as fun to use.

And, to your point about it looking like ActionScript (I did some Flash as well back in the day), the language has really evolved. If you remove the type annotations, ColdFusion (at least its script-form) looks no different from JavaScript - my other favorite language. So it has relatively little cognitive load going back-and-forth between the two.

One thing about ColdFusion that I really love is that it's blocking by default. On the client-side, it's essential that JavaScript is non-blocking. But on the server, I've always found non-blocking code harder to hold in my head. The fact that ColdFusion is blocking on the server when you want it, and can also by async when you need it, is a best-of-both-worlds scenario.

That said, the async/await functionality in JavaScript / Node makes that less of a sticking point in more modern code.

Post A Comment — I'd Love To Hear From You!

I believe in love. I believe in compassion. I believe in human rights. I believe that we can afford to give more of these gifts to the world around us because it costs us nothing to be decent and kind and understanding. And, I want you to know that when you land on this site, you are accepted for who you are, no matter how you identify, what truths you live, or whatever kind of goofy shit makes you feel alive! Rock on with your bad self!
— Ben Nadel
Managed ColdFusion hosting services provided by:
xByte Cloud Logo