CFLib.org – Common Function Library Project

StructRenameKey(struct, key, newkey[, allowOverwrite])

Last updated June 26, 2002

author

Erki Esken

Version: 1 | Requires: CF5 | Library: DataManipulationLib

Description:
Renames a specified key in the specified structure. You can optionally choose if overwriting existing key is allowed or not (by default overwriting is not allowed).

Return Values:
Returns a structure.

Example:

<cfscript>
	foo = StructNew();
	foo["foo"] = ArrayNew(1);
	foo["foo"][1] = "foo one";
	foo["foo"][2] = "foo two";
	foo["bar"] = "bar";
	foo["foobar"] = "foobar";
</cfscript>

Original:
<cfdump var="#foo#">

<br>

Renamed (allowoverwrite = false):
<cfset foo = StructRenameKey(foo, "foo", "foobar")>
<cfdump var="#foo#">

<br>

Renamed (allowoverwrite = true):
<cfset foo = StructRenameKey(foo, "foo", "foobar", true)>
<cfdump var="#foo#">

Parameters:

Name Description Required
struct The structure to modify. Yes
key The key to rename. Yes
newkey The new name of the key. Yes
allowOverwrite Boolean to determine if an existing key can be overwritten. Defaults to false. No

Full UDF Source:

/**
 * Renames a specified key in the specified structure.
 * 
 * @param struct 	 The structure to modify. (Required)
 * @param key 	 The key to rename. (Required)
 * @param newkey 	 The new name of the key. (Required)
 * @param allowOverwrite 	 Boolean to determine if an existing key can be overwritten. Defaults to false. (Optional)
 * @return Returns a structure. 
 * @author Erki Esken (erki@dreamdrummer.com) 
 * @version 1, June 26, 2002 
 */
function StructRenameKey(struct, key, newkey) {
	// Allow overwriting existing keys or not?
	var AllowOverWrite = false;
	switch (ArrayLen(Arguments)) {
		case "4":
			AllowOverWrite = Arguments[4];
	}

	// No key or keys are the same? Return.
	if (NOT StructKeyExists(struct, key) OR CompareNoCase(key, newkey) EQ 0)
		return struct;

	if (NOT AllowOverWrite AND StructKeyExists(struct, newkey)) {
		// New key already exists and overwriting is off? Return.
		return struct;
	} else {
		// Duplicate and delete old. Return.
		struct[newkey] = Duplicate(struct[key]);
		StructDelete(struct, key);
		return struct;
	}
}
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