我正在尝试过滤和重新排序哈希数组。过滤器和顺序由另一个字符串数组定义,它们表示"slug"
哈希键的值。结果数组应仅包含其"slug"
键值包含在 slugs 数组中并按相同顺序排序的哈希值。如果我有第一个数组:
data = [
{
"slug" => "lemon",
"label" => "Lemon Label"
},
{
"slug" => "table",
"label" => "Table Label"
},
{
"slug" => "peach",
"label" => "Peach Label"
},
{
"slug" => "strawberry",
"label" => "Strawberry Label"
},
{
"slug" => "bread",
"label" => "Bread Label"
},
{
"slug" => "orange",
"label" => "Orange Label"
}
]
第二个数组为:
ordered_keys = ["orange", "lemon", "strawberry"]
那么,结果应该是这样的数组:
result = [
{
"slug" => "orange",
"label" => "Orange Label"
},
{
"slug" => "lemon",
"label" => "Lemon Label"
},
{
"slug" => "strawberry",
"label" => "Strawberry Label"
}
]
我设法通过以下方式获得了过滤功能:
result = data.select{|x| ordered_keys.include? x.slug}
但我找不到一个聪明的方法来订购一个。有任何想法吗?