CFLib.org – Common Function Library Project

structMerge(struct1, struct2)

Last updated March 2, 2006

author

Marcos Placona

Version: 1 | Requires: CF6 | Library: DataManipulationLib

Description:
This UDF can be used when you want to merge two ColdFusion Structures on just one. Just pass the structures as arguments, and it returns a new structure with all the data amended or merged. Unlike structAppend, existing values in struct1 will be appended, not overwritten.

Return Values:
Returns a struct.

Example:

<cfset str1 = structNew() />
<cfset str1.name = "Marcos" />
<cfset str1.surname = "Placona" />
<cfset str1.age = 22 />
<cfset str1.wife = false />
<cfset str1.dog = "Toby" />
<cfset str1.company = "Company 1">

<cfset str2 = structNew() />
<cfset str2.name = "John" />
<cfset str2.surname = "Doe" />
<cfset str2.age = 55 />
<cfset str2.children = 2 />
<cfset str2.company = "Company 2">
<cfset str2.website = "www.mywebsite.co.uk">

<cfdump var="#structMerge(str1,str2)#" label="structMerge">
<cfset structAppend(str1, str2)>
<cfdump var="#str1#" label="structAppend">

Parameters:

Name Description Required
struct1 The first struct. Yes
struct2 The second struct. Yes

Full UDF Source:

<!---
 Merge two simple structures in one combining keys or creating new ones.
 
 @param struct1 	 The first struct. (Required)
 @param struct2 	 The second struct. (Required)
 @return Returns a struct. 
 @author Marcos Placona (marcos.placona@gmail.com) 
 @version 1, March 2, 2006 
--->
<cffunction name="structMerge" output="false">
	<cfargument name="struct1" type="struct" required="true">
	<cfargument name="struct2" type="struct" required="true">
	<cfset var ii = "" />
	
	<!--- Loop over the second structure passed --->
	<cfloop collection="#arguments.struct2#" item="ii">
		<cfif structKeyExists(struct1,ii)>
		<!--- In case it already exists, we just update it --->
			<cfset struct1[ii] = listAppend(struct1[ii], struct2[ii])>
		<cfelse>
		<!--- In all the other cases, just create a new key with the values or list of values --->
			<cfset struct1[ii] = struct2[ii] />
		</cfif>
	</cfloop>
	<cfreturn struct1 />
</cffunction>
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