Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ColdFusion sort structure by key

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

like image 941
user6824563 Avatar asked Apr 21 '26 19:04

user6824563


1 Answers

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.

like image 61
Alex Avatar answered Apr 24 '26 17:04

Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!