Ruby-如何根据嵌套哈希项目的值对数组排序?

问题描述 投票:2回答:3

我要做一些相当复杂的排序。

给定一个哈希数组,我需要根据每个哈希键的值对数组内的哈希进行排序。

例如(以JSON格式给出::

"instruments":[
{"id":1,"title":"Piano","token":"piano","count":13},
{"id":6,"title":"Bass Guitar","token":"bass","count":12},
{"id":11,"title":"Viola","token":"viola","count":12},
{"id":4,"title":"Synth","token":"synth","count":11},
{"id":3,"title":"Keyboard","token":"keyboard","count":9},
{"id":7,"title":"Saxophone","token":"saxophone","count":8},
{"id":12,"title":"Flute","token":"flute","count":8},
{"id":5,"title":"Drums","token":"drums","count":6},
{"id":2,"title":"Guitar","token":"guitar","count":5},
{"id":8,"title":"Violin","token":"violin","count":5},
{"id":9,"title":"Vocals","token":"vocals","count":4},
{"id":10,"title":"Cello","token":"cello","count":4}
]

此JSON是Rails中responds_with的结果。在此之前,我想根据每个哈希中"title"键的字母顺序在数组中切换这些哈希值。

下面是JSON(在Firebug中)的一部分的屏幕截图,目的是更好地说明我的意思:

“在此处输入图像说明”“ >>

任何帮助将不胜感激。

谢谢!

我要做一些相当复杂的排序。给定一个哈希数组,我需要根据每个哈希键中的值对数组中的哈希排序。例如(以JSON格式给出):“ ...

ruby-on-rails ruby json
3个回答
5
投票

您正在寻找Enumerable#sort_by


0
投票

0
投票

如果有帮助的人,我的JSON是双重嵌套的

© www.soinside.com 2019 - 2024. All rights reserved.