Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coldfusion Struct getting only numeric key list

I have a coldfusion Struct containing mix keys numeric and alpha, alphanumerics

I need to access only the numeric keys.

My code looks like

<cfset ids = structkeyList(st ) />
<cfset numericIDs = "" />
<cfloop list="#ids#" index="i">
    <cfif IsNumeric(i)>
        <cfset numericIDs = ListAppend( numericIDs , i ) />
    </cfif>
</cfloop>

Is there a better method to solve such problems?

like image 376
user3733648 Avatar asked Nov 26 '15 11:11

user3733648


2 Answers

Is there a better method to solve such problems?

I would use something like this:

<cfset numericIDs = arrayToList(reMatch('\b\d+(?=,|$)\b', structKeyList(st)))>
like image 57
Beginner Avatar answered Sep 20 '22 00:09

Beginner


Is there a better method to solve such problems?

I'd generally recommend working with arrays instead of lists.

In CF9 a loop similar to yours is as good as it gets. You can make a utility function out of it if you need it more than once. This one avoids StructKeyList() to be able to deal with all kinds of keys, independent of a separator character:

<cfscript>
  function GetNumericKeys(struct) {
    var keys = struct.keys();
    var result = ArrayNew(1);
    var key = "";

    while (keys.hasNext()) {
      key = keys.next();
      if (IsNumeric(key)) ArrayAppend(result, key);
    }

    return result;
  }
</cfscript>

and

<cfset nkeys = GetNumericKeys(st)>

In CF11 you can get a little more sophisticated (tested on CF11, can't say how CF10 handles this code).

<cfscript>
  numericIDs = arrayFilter(structKeyArray(st), function (key) {
    return IsNumeric(key);
  });
</cfscript>

To ensure integer keys, use:

<cfscript>
  numericIDs = arrayFilter(structKeyArray(st), function (key) {
    return Int(key) eq key;
  });
</cfscript>
like image 39
Tomalak Avatar answered Sep 22 '22 00:09

Tomalak