Nebu
Nebu

Reputation: 1793

Sort a nested structure in Coldfusion

I am trying to sort a nested struct using StructSort. Below is a simple example of what I am trying to do. The code below does not work and returns the following error "The specified element a does not contain a simple value." Is it possible to sort a nested structure in Coldfusion, and if so how?

<cfscript>
   data = {"a":{"name":100},"b":{"name":50},"c":{"name":25},"d":{"name":75}};
   dataSorted= StructSort(data, function(a,b) {
    return compare(a.name, b.name);
   });
   writeDump(dataSorted);
</cfscript>

expected output

  1. c
  2. b
  3. d
  4. a

Also made a cffiddle here: https://cffiddle.org/app/e20a782a-be90-4e65-83de-e31eb83fdf4f

Upvotes: 1

Views: 463

Answers (1)

accidentalcaveman
accidentalcaveman

Reputation: 127

Docs: https://docs.lucee.org/reference/objects/struct/sort.html

<cfscript>
   data = {
       "a": {"name": 100},
       "b": {"name": 50},
       "c": {"name": 25},
       "d": {"name": 75}
   };

    dataSorted = data.sort("numeric", "asc", "name")

    writeDump(dataSorted);
</cfscript>

Result: array ["c", "b", "d", "a"]

This worked for me on lucee 5. something. The last argument in the sort function is the pathToSubElement within a struct. Fo your example it is simply one level deep using the name property.

Upvotes: 1

Related Questions