【问题标题】:Format the array with hashes用哈希格式化数组
【发布时间】:2014-04-25 09:23:29
【问题描述】:

我必须得到这样的数组

 [{"social"=>"linkedin", "count"=>1},
 {"social"=>"twitter",   "count"=>1}, 
 {"social"=>"facebook",  "count"=>0}]

来自这个数组

=> [{"twitter"=>1, "linkedin"=>1, "facebook"=>0}]

我该怎么做?

【问题讨论】:

  • @sawa SQL 查询返回我数组,但我需要在视图中使用之前对其进行格式化。仅此而已)还有什么不清楚的?我得到了答案)tnx
  • 问题不清楚。这背后的逻辑是什么?
  • 顺便说一句,你接受的答案并没有给出你想要的。
  • 嗯,为什么? result => [{"twitter"=>1, "linkedin"=>1, "facebook"=>0}]result[0].map { |key, value| {'social' => key, 'count'=>value } }=> [{"social"=>"twitter", "count"=>1}, {"social"=>"linkedin", "count"=>1}, {"social"=>"facebook", "count"=>0}]
  • 我想要的样子

标签: ruby-on-rails ruby arrays ruby-on-rails-4


【解决方案1】:

你可以试试:

arr = [{"twitter"=>1, "linkedin"=>1, "facebook"=>0}]

arr[0].map { |key, value| {'social' => key, 'count'=>value } }
# => [{"soсial"=>"twitter", "count"=>1}, {"soсial"=>"linkedin", "count"=>1}, {"soсial"=>"facebook", "count"=>0}]

【讨论】:

    【解决方案2】:

    如下:

    [{"twitter"=>1, "linkedin"=>1, "facebook"=>0}].first.to_a.map do |a|
      { "sotial" => a[0], "count" => a[1] } 
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-28
      • 2021-12-22
      相关资源
      最近更新 更多