I have array of structures where I should access specific field. Here is example of my data:
array
1
struct
address_city Washington
address_state DC
array
2
struct
address_city New York
address_state NY
array
3
struct
address_city Miami
address_state FL
I have this code to loop over array and then inner loop to iterate over structures:
<cfloop from="1" to="#arrayLen(arrData)#" index="i">
<cfset data = arrData[i]>
<cfloop collection="#data#" item="key">
<cfoutput>#key#:#data[key]#<br></cfoutput>
</cfloop>
</cfloop>
Code above will produce this output:
address_city:Washington
address_state:DC
address_city:New York
address_state:NY
address_city:Miami
address_state:FL
Instead I need to access only address_state
value. I have tried something like this:
<cfloop from="1" to="#arrayLen(arrData)#" index="i">
<cfset data = arrData[i]>
<cfloop collection="#data#" item="key">
<cfoutput>#data[key]['address_state']#<br></cfoutput>
</cfloop>
</cfloop>
Then I was getting this error message:
Message You have attempted to dereference a scalar variable of type class java.lang.String as a structure with members.
Is there a way to output only one field from each structure in array? Something similar is doable in JavaScript when iterating over JS Object. Example:
for (var key in data) {
console.log(data[key]['address_state']);
}
If anyone knows the way to achieve this in ColdFusion please let me know.
Funny enough, there is a way to do it almost exactly like the JS example.
for (key in data) {
writeOutput( "Address State = " & key.address_state & "<br>");
}
https://trycf.com/gist/f0bd28bbf644912d320b10fdc5f526f4/acf?theme=monokai
You were getting the error because you were referencing the data
array when you didn't need to. You were already looping through the key
s in data
by nature of your loop. In your script example, you didn't need to do a double loop through your array.