如何在rails中循环使用多维数组



我正在我的项目中实现searchkick,并使搜索工作正常。现在我正在尝试实现一个过滤系统,并使用aggs来显示过滤条件。aggs返回的数组对我来说有点复杂,我正试图弄清楚如何在特定部分中循环。以下是它返回的标签:

{"technologies"=>{"doc_count_error_upper_bound"=>0,"sum_other_doc_count"=>0,"buckets"=>[{"key"=>"油炸","doc_count"=>1},{"key"=>"Searing","doc_coount"=>1}},"components"=>{"doc_count_error_upper_bound"=>0,"sum_other_doc_count"=>0,"buckets"=>[{"key"=>"Furikake,用于服务","doc_count"=>1},{"key"=>"犹太盐和黑胡椒粉","doc_count"=>1},{"key"=>"三文鱼柳","doc_coount"=>1},{"key"=>"鳄梨,切丁","doc_count"=>1},{"key"=>"熟白大米","doc_count"=>1},{"key"=>"日本黄瓜","doc_count"=>1},{"key"=>"红烧酱"、"doc_count"=>1}、{"key"=>"至8个葱段,薄片","doc_count"=>1},{"key"=>"植物油","doc_count"=>1}]},"菜系"=>{"doc_count_error_upper_bound"=>0,"sum_other_doc_count"=>0,"buckets"=>[{"key"=>"Asian","doc_count"=>1},{"key"=>"日语","doc_coount"=>1{]]}

我该如何写一个do循环,只遍历烹饪部分,并从桶中提取个人姓名和计数:

"菜系"=>{"doc_count_error_upper_bound"=>0,"sum_other_doc_count"=>0,"buckets"=>[{"key"=>"Asian","doc_count"=>1},{"key"=>"日语","doc_coount"=>1{]]}

所以基本上我想要一个列表,看起来像这样:亚洲人(1(日语(1(

您所拥有的是一个带有数组元素的散列。这取决于你到底想要什么,但假设你给它分配了一个变量my_hash,你可以这样做,例如:

my_hash['cuisines']['buckets'].reduce('') do |r, h| 
  r += "#{h['key']} (#{h['doc_count']}) "
end
=> "Asian (1) Japanese (1) "

相关内容

  • 没有找到相关文章

最新更新