Reputation: 815
How can I sort a coldfusion structure by key not value.
structSort(struct, "text", "asc")
It sorts the values, but I would like to sort the key.
Does anyone know how to do it?
Thanks
Upvotes: 3
Views: 4054
Reputation: 7833
If you are on CF2016, you can use structNew("ordered")
to create a struct that keeps its insertion order.
orderedStruct = structNew("ordered");
structKeys = structKeyArray(struct);
arraySort(structKeys, "text", "asc");
for (key in structKeys) {
orderedStruct[key] = struct[key];
}
writeDump(orderedStruct);
On older versions of CF, you have to rely on Java's LinkedHashMap.
orderedStruct = createObject("java", "java.util.LinkedHashMap").init();
But beware of orderedStruct
key names now being case sensitive! Also note that dumping a struct will display the entries alphabetically. However, looping over the struct would yield the correct order.
Upvotes: 9