Kokesh
Kokesh

Reputation: 3263

How to get dynamic property names?

I've got array of key names and a structure containing the data. I need to loop through the structure and print out all the property values, based on the key-array. my key value contains for example values

propList array contains:
id, name, haircolor, age

I want to go through the structure and print out values for

item.id
item.name
item.haircolor
item.age
(or any properties stored in the array)

I've tried to print out

<cfoutput>"#item.propName#"</cfoutput>

where propName is retrieved from looping through propList array.

Upvotes: 0

Views: 188

Answers (3)

Mark D
Mark D

Reputation: 543

Do you have an array of structures or something? if you only have one level of properties in the structure you don't need the two loops? You just have to do:

<cfloop array="#myStructures#" item="item">
    <cfloop array="#propList#" index="key">
        <cfoutput>#item[key]#</cfoutput>
    </cfloop>
</cfloop>

Or to be safer:

<cfloop array="#myStructures#" item="item">
    <cfloop array="propList" index="key">
        <cfif StructKeyExists(item, key)>
        <cfoutput>#item[key]#</cfoutput>
        </cfif>
    </cfloop>
</cfloop>

Upvotes: 3

Scott Stroz
Scott Stroz

Reputation: 7519

You can use array notation to get values form a structure when the key is 'dynamic'.

<cfloop index="item" array=#input#>
    <cfloop list="#rawColumnList#" delimiters="," index="value">
        <cfoutput>#item[ value ]#</cfoutput>
    </cfloop>
</cfloop>

Upvotes: 2

Kokesh
Kokesh

Reputation: 3263

a solution:

<cfloop index="item" array=#input#>
    <cfloop list="#rawColumnList#" delimiters="," index="value">
        <cfset output=Evaluate("item.#value#")>
        <cfoutput>#output#</cfoutput>
    </cfloop>
</cfloop>

Upvotes: -4

Related Questions