structEach
Used to loop over elements in a structure by accessing key-value pairs.
structEach(struct,function(key, value [, struct]){} [, parallel] [, maxThreads]) → returns void
Member Function Syntax
someStruct.each(function(key, value [, struct]){} [, parallel] [, maxThreads])
Argument Reference
struct string Required
Structure or a variable that contains one.
callback any Required
Closure or a function reference that will be called for each of the iteration.
Callback parameters:
-
key* string : The key for the current iteration -
value* any : The value for the current iteration -
struct* struct : A reference of the original struct
parallel boolean
Default: false
false
Lucee 4.5+ true if the items can be executed in parallel
Values:
truefalse
maxThreads numeric
Default: 20
20
Lucee 4.5+ the maximum number of threads to use when parallel = true
Links more information about structEach
- Map, Reduce and other Higher Order Functions - A Primer for map, reduce, filter, and Higher Order Functions in general.
- ColdFusion 11: .map() and .reduce() - A look at the new .map() and .reduce() methods that each of array, struct and lists all have
Examples Sample code invoking the structEach function
Use a function to write out the keys in a structure to the screen
someStruct = {a=1,b=2,c=3};
structEach(someStruct,function(key,value) {
writeOutput('Key ' & key & ' is ' & value & '; ');
}); Expected Result: Key a is 1; Key b is 2; Key c is 3;
favs = {color: 'blue', food: 'pizza', sport: 'basketball'};
// named function
// notice that the function takes two arguments, the key and value pair of the current iteration of the structure's key-value pairs
function getFavorites(key, value) {
writeOutput('My favorite ' & key & ' is ' & value);
}
// run structEach() with a named function
structEach(favs,getFavorites);
// run structEach() with an inline function
structEach(favs, function(key,value) {
writeOutput('My favorite ' & key & ' is ' & value);
});
CF 11+ Lucee 4.5+
statusCodes = {
OK = 200,
CREATED = 201,
NOT_MODIFIED = 304,
BAD_REQUEST = 400,
NOT_FOUND = 404
};
statusCodes.each(function(key, value) {
writeOutput("#key# => #value#<br />");
}); Expected Result: NOT_FOUND => 404 BAD_REQUEST => 400 CREATED => 201 OK => 200 NOT_MODIFIED => 304
Lucee 4.5+
statusCodes = {
OK = 200,
CREATED = 201,
NOT_MODIFIED = 304,
BAD_REQUEST = 400,
NOT_FOUND = 404
};
statusCodes.each(function(key, value, struct) {
writeDump(struct);
});
© 2012–present Foundeo, Inc. and the CFDocs contributors.
Licensed under the MIT License.
ColdFusion is a trademark of Adobe Systems Incorporated.
https://cfdocs.org/structeach