user4998533
user4998533

Reputation:

Looping over a nested structures containing arrays

I know this question might have many answers, but I have been unable to solve it so far. I want to loop over structures which contain in some fields arrays and within those arrays, additional structures.

I attached a screenshot of the structures.

Currently the problem seems complex and I have not found a solution.

The image is located below:

http://i.imgur.com/4XPOAJp.png

Tried this below:

<cfloop collection="#qEvents#" item="ii">
<cfoutput>
#ii# - #qEvents[ii]#
</cfoutput>
</cfloop>

but got an error at the end like:

Complex object types cannot be converted to simple values.

Upvotes: 0

Views: 1033

Answers (2)

Paul Sturm
Paul Sturm

Reputation: 2138

You'll have to inspect each item before you do something with it. isStruct and isArray is your friend. Once you find a structure, you'll loop its keys, and for an array you'll loop by index and length of array.

Upvotes: 0

John Whish
John Whish

Reputation: 3036

Not quite sure what your desired output is, but assuming you are just trying to loop through and display the structure then you can do something like this. Hopefully it'll give you an idea of how to deal with nested structures and you can go from there :)

<cfscript>
// example data
qEvents = {
  "attendees" = [{
      "displayName" = "Tom",
      "id" = 1,
      "self" = true
    },{
      "displayName" = "Richard",
      "id" = 2,
      "organizer" = true
    }],
  "creator" = {
    "displayName" = "Harry"
  }
};

// process the data
function showStructure(it) {
  if (IsSimpleValue(it)) {
    return it; // just a simple string
  } else {
    var result = "";
    var isStruct = isStruct(it);
    for (var v in it) {
      if (isStruct) {
        result &= v & " = " & showStructure(it[v]) & chr(10);
      } else { 
        // assuming an array here but could be more complex
        result &= showStructure(v) & chr(10);
      }
    }
    return result;
  }
}
</cfscript>

<cfoutput>

<cfloop collection="#qEvents#" item="key">
  <cfset keyValue = qEvents[key]>
  <b>#key#</b>:<br>
  #replace(showStructure(keyValue), chr(10), "<br>", "all")#<hr> 
</cfloop>

</cfoutput>

Here's an example of it in action on the excellent trycf site: http://trycf.com/gist/d71e418802cefe93ae51/acf?theme=monokai

Upvotes: 2

Related Questions