Copying Structures in Coldfusion

Coldfusion has the feature of creating structures which is a JSON like key-value pair variable, essentially used to store multiple variables as a single collection. There are different ways to copy structures in coldfusion and there are differences between them as well.

Following are some of the ways in which one can copy structures in Coldfusion:

1. Direct Variable to Variable copy. (Copy By Reference)

Let’s say we have an empty variable copyStruct and a structure originalStruct.

This approach of copying variable is as simple as initializing the variable copyStruct by originalStruct

Keep in mind that after this, copyStruct is a referenced copy of originalStruct.
in simpler terms, any changes made to copyStruct will reflect in originalStruct and any changes in originalStruct will reflect in copyStruct.

2. StructCopy(). Copy by value at top level, but copy by reference for any structures inside the structure.

Taking the example in the first case, let’s say that the structure originalStruct has the following key value pairs.

key1 : "value 1", 
key2 : "value 2",
key3 : {nestedKey1: "nestedValue1"
nestedKey2: "nestedValue2"
}

The copy in using structCopy can be done by:

After doing this, if you change the value of key1 or key2 in copyStruct, the changes will not reflect in key1 and key2 in originalStruct. but if you make any changes to the values in key3 in copyStruct , the changes will reflect in key3 in originalStruct, and any changes to values in key3 inoriginalStruct will reflect in key3 in copyStruct. StructCopy() copies the top level keys by value and any structures inside by reference. This is a hybrid approach between copy by value and copy by reference.

3.Duplicate(). Pure Copy by Value

The third way to copy a structue to another variable is by using the Duplicate() function, again taking the above example, this can be done by:

 

In this case copyStruct and originalStruct aren’t connected at all, any changes to one will not reflect in the other, copyStruct will have all the keys and values inoriginalStruct but it is not connected to originalStruct in anyway.

150 150 Burnignorance | Where Minds Meet And Sparks Fly!