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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With