Merge Structs in ColdFusion

Another helper function for ColdFusion, this one to replicate PHP's array_merge which allows you to merge multiple arrays. In this case I'm only concerned with associative arrays, which ColdFusion calls structs.

CFMX provides StructAppend which will merge two (and only two) structures, optionally overwriting keys. I always want to overwrite keys, and I want to merge unlimited structures.

<cfscript>
function struct_merge() {
	var base = {};
	var i = 1;
 
	for( i = 1; i LTE ArrayLen(arguments); i=i+1 ) {
		if( IsStruct(arguments[i]) ) {
			StructAppend(base, arguments[i], true);
		}
	}
	return base;
}
</cfscript>

Usage

<cfscript>
one = {
	a = "a",
	b = "b",
	c = "c",
	d = "d",
	e = "e"
};
 
two = {
	1 = "one",
	2 = "two",
	3 = "three",
	4 = "four",
	a = "one_SetByTwo",
	c = "three_SetByTwo"
};
 
three = {
	a = "one_SetByThree",
	2 = "b_SetByThree"
};
 
new = struct_merge(one, two, three);
</cfscript>
<cfdump var=#new#>

Result:

 

Tags: , , ,

One Response to “Merge Structs in ColdFusion”

  1. Jason Blum Says:

    Hey how about sharing this and related stuff you've been playing with at CHUG next Thursday: http://capitolhillusergroup.org/ ? Remember, we're meeting virtually now at http://adobechats.adobe.acrobat.com/chug...

Leave a Reply


© 2007-2012, Corey Gilmore | Posts RSS Feed | Comments RSS Feed | Contact

 

The views expressed on these pages are mine alone and not those of any past or present employer. All information presented on this site was obtained lawfully and not through disclosure under the terms of an NDA.