structEach

Used to loop over elements in a structure by accessing key-value pairs.

structEach(struct,function(key, value [, struct]) {})

Member Function Syntax

someStruct.each(function(key, value [, struct]) {})

Argument Reference for the structEach function

structure

Required: Yes
Structure or a variable that contains one.

callback

Required: Yes
Closure or function reference that will be called for each iteration. The arguments passed to the callback are:

key: Name of the key in the struct
value: Value of the key in the struct
struct: Lucee 4.5+ A reference to the original struct

Links more information about structEach

Examples sample code invoking the structEach function


structEach() with an inline function (closure)

Use a function to write out the keys in a structure to the screen

someStruct = {a=1,b=2,c=3};

arrayEach(someStruct,function(obj) {
     writeOutput('Key ' & key & ' is ' & value & '; ');
});

Expected Result: Key a is 1; Key b is 2; Key c is 3;


Using a function reference

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); 
 }); 

Using the member function

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


Accessing a reference to the looping struct in the callback

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);
});

Fork me on GitHub