coldfusion - Any better way to loop through a collection (struct) in CFML? -
please have @ code block below:
<cfset index = 0 /> <cfloop collection="#anotherperson#" item="key" > <cfset index = index+1 /> <cfoutput> #key# : #anotherperson[key]# <cfif index lt arraylen(structkeyarray(anotherperson))> , </cfif> </cfoutput> </cfloop> <!--- result age : 24 , haar : blondes haar , sex : female , ort : hanau ---->
now can please tell me how achieve same result without setting index outside , incrementing inside loop? if notice carefully, had write 2 more cfset tag , 1 cfif tag expensive code avoid comma (,) @ end of collection!
ok, i'm showing 2 answers. first run on coldfusion 9. since other people might find thread , using lucee server or newer version of adobe coldfusion, i'm including one-liner uses higher order functions , runs on acf 2016. there's lot of syntactic sugar (like member functions) , functional programming you're missing being on cf9. these answers use script, because manipulating data not view (where tags/templating used).
set data
mystruct = { 'age'=24, 'haar'='blondes haar', 'sex'='female', 'ort'='hanau' };
cf9 compat, convert data array , use delimiter add commas
myarray = []; for( key in mystruct ) { arrayappend( myarray, key & ' : ' & mystruct[ key ] ); } writeoutput( arraytolist( myarray, ', ' ) );
modern cfml. use struct reduction closure convert each key aggregated array turned list.
writeoutput( mystruct.reduce( function(r,k,v,s){ return r.append( k & ' : ' & s[ k ] ); }, [] ).tolist( ', ' ) );
Comments
Post a Comment