Coldfusion Struct retrieves only a numeric key list

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

I need to access only 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 way to solve such problems?

+6
source share
4 answers

Is there a better way to solve such problems?

I would use something like this:

 <cfset numericIDs = arrayToList(reMatch('\b\d+(?=,|$)\b', structKeyList(st)))> 
+6
source

Is there a better way to solve such problems?

I usually recommend working with arrays instead of lists.

In CF9, the loop is like yours, as good as it gets. You can make it a useful function if you need it more than once. This avoids StructKeyList() in order to be able to handle all types of keys, regardless of the delimiter 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 complicated (tested on CF11, I can’t say how CF10 handles this code).

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

To provide whole keys, use:

 <cfscript> numericIDs = arrayFilter(structKeyArray(st), function (key) { return Int(key) eq key; }); </cfscript> 
+4
source

I really do not understand what is wrong with this. It should work well already, and it is very readable.

Sometimes working with a list is faster than an array.

0
source

I had this:

 <cfscript> function ListNumeric(principal) { a=principal; cleanlist = ''; for (i=1; i <= ListLen(a);i=i+1) { if(IsNumeric(ListGetAt(a,i))){ cleanlist = ListAppend(cleanlist,ListGetAt(a,i)); } } Return cleanlist; } </cfscript> 

It is also possible to work with regex:

 inList2 = REReplace(inList,"[^0-9.]", "","ALL"); 
0
source

All Articles