CFLib.org – Common Function Library Project

structFindKeyWithValue(struct, key, value[, scope])

Last updated September 09, 2013

author

Adam Cameron

Version: 1 | Requires: CF9 | Library: UtilityLib

Description:
Often I need to find keys with specific values from with a given structure, so this combines both structFindKey() and structFindValue()

Return Values:
Returns an array as per structFindValue()

Example:

numbers = {
    one        = "tahi",
    two        = [
        {rua="two"},
        {rua="deux"}
    ],
    three    = [
        {toru="three"},
        {toru="trois"},
        {toru="drei"}
    ],
    wha = "four",
    duplicates = [
        {rua="two"},
        {toru="trois"}
    ]
};

result = structFindKeyWithValue(
    numbers,
    "rua",
    "two",
    "ALL"
);

Parameters:

Name Description Required
struct Struct to check Yes
key Key to find Yes
value Value to find for key Yes
scope Whether to find ONE (default) or ALL matches No

Full UDF Source:

/**
 * Combines structFindKey() and structFindValue()
 * v1.0 by Adam Cameron
 * v1.01 by Adam Cameron (fixing logic error in scope-handling)
 * 
 * @param struct      Struct to check (Required)
 * @param key      Key to find (Required)
 * @param value      Value to find for key (Required)
 * @param scope      Whether to find ONE (default) or ALL matches (Optional)
 * @return Returns an array as per structFindValue() 
 * @author Adam Cameron (dac.cfml@gmail.com) 
 * @version 1.01, September 9, 2013 
 */
public array function structFindKeyWithValue(required struct struct, required string key, required string value, string scope="ONE"){
    if (!isValid("regex", arguments.scope, "(?i)one|all")){
        throw(type="InvalidArgumentException", message="Search scope #arguments.scope# must be ""one"" or ""all"".");
    }
    var keyResult = structFindKey(struct, key, "all");
    var valueResult = [];
    for (var i=1; i <= arrayLen(keyResult); i++){
        if (keyResult[i].value == value){
            arrayAppend(valueResult, keyResult[i]);
            if (scope == "one"){
                break;
            }
        }
    }
    return valueResult;
}

Search CFLib.org


Latest Additions

Raymond Camden added
QueryDeleteRows
November 04, 2017

Leigh added
nullPad
May 11, 2016

Raymond Camden added
stripHTML
May 10, 2016

Kevin Cotton added
date2ExcelDate
May 05, 2016

Raymond Camden added
CapFirst
April 25, 2016

Created by Raymond Camden / Design by Justin Johnson