Using sort throws away keys in a range

When doing a range on a group/array of items, I like to use the key in the range loop for creating links. The key values may be like
{ "abc": { "somedata": True, "sort_order": 2 }, "def": { "some_data": True, "sort_order": 1 }, "ghi": { "somedata": True, "sort_order": 3 } }

Which should give me the keys of “abc”, “def”,“ghi” when I do
range $key, $item := .Params.thearray

This works fine until I change the range to be
range $key, $item := .Params.thearray | .Params.thearray "sort_order".
The keys from $keys are now 1,2,3 instead. Can I either preserve the keys, or store them and still be able to use them?

Hi @SuperRoach. If you organize your data differently by putting your keys as values (since you’re using them as values) then you can overcome this.

I guess the problem I had was the expected behaviour was to still have the keys, which are there before the sort, and a handy value that is exposed and documented. I did not expect to have them be altered in this way and there was no mention of it in the docs itself. Without changing my source data, I don’t think sort would be something I could use which feels against the ease of use aim for hugo.

Straight from the docs :slight_smile:

A sorted array of map values will be returned with the keys eliminated.

1 Like