合并哈希数组并重新排序

时间:2019-05-15 16:04:28

标签: ruby-on-rails ruby hash

我的哈希表看起来很像

arr = [
  {"partner_name"=>"Bell", "publisher_name"=>"News - Calgary", "mn"=>"", "mid"=>415},
  {"partner_name"=>"Bell", "publisher_name"=>"News - Vancouver Island", "mn"=>"Module 2.0 ", "mid"=>4528},
  {"partner_name"=>"Bell", "publisher_name"=>"News - Atlantic", "mn"=>"Module 2.0 ", "mid"=>4531},
  {"partner_name"=>"Bell", "publisher_name"=>"News - Kitchener", "mn"=>"Module 2.0 ", "mid"=>4535},
  {"partner_name"=>"Bell", "publisher_name"=>"News - London", "mn"=>"Module 2.0 ", "mid"=>4536},
  {"partner_name"=>"Bell", "publisher_name"=>"News - Ottawa", "mn"=>"Module 2.0 ", "mid"=>4539},
  {"partner_name"=>"Bell", "publisher_name"=>"News - Regina", "mn"=>"Module 2.0 ", "mid"=>4540},
  {"partner_name"=>"Bell", "publisher_name"=>"News - Saskatoon", "mn"=>"Module 2.0 ", "mid"=>4541},
  {"partner_name"=>"Bell", "publisher_name"=>"News - Toronto", "mn"=>"Module 2.0 ", "mid"=>4542},
  {"partner_name"=>"Bell", "publisher_name"=>"News - Windsor", "mn"=>"Module 2.0 ", "mid"=>4544},
  {"partner_name"=>"Bell", "publisher_name"=>"CP24", "mn"=>"Module 2.0 Platform", "mid"=>5413},
]

我尝试做arr.group_by{|el|el['partner_name']}

我想达到这个结果

{
  partner:'Bell',
  publishers: [
    {name:'News - Vancouver Island'},
    {name:'News - Vancouver Island'},
    # ... and others
  ],
  modules:[
    {mn: val, mid: id_val},
    # ...
  ],
}

3 个答案:

答案 0 :(得分:1)

这样的事吗?

arr.group_by { |item| item["partner_name"] }.
    map do |partner_name, data| 
      publishers = data.map { |h| Hash[:name, h["publisher_name"]] }
      modules = data.map { |h| Hash[:mn, h["mn"], :mid, h["mid"]] }
      Hash[:partner, partner_name, :publishers, publishers, :modules, modules] 
    end

答案 1 :(得分:1)

group_by和地图

result = arr.
  group_by { |r| r["partner_name"] }.
  map do |(partner_name, records)|
    {
      name: partner_name,
      publishers: records.map do |r|
        { name: r["publisher_name"] }
      end,
      modules: records.map do |r|
        { mn: r["mn"], mid: r["mid"] }
      end,
    }
  end

答案 2 :(得分:0)

由于数组中的哈希值似乎已经成为合作伙伴的范围,因此简单的实现可能类似于:

new_h = {partner: arr.first["partner_name"],publishers: [],modules: []}
arr.each_with_object(new_h) do |h, result| 
  result[:publishers] << {name: h["publisher_name"]}
  result[:modules] << h.slice("mn","mid")
end

如果它们的作用域没有如图所示,则只需对其进行分组和映射:

arr.group_by {|h| h["partner_name"]}.map do |name,values|
  new_h = {partner: name,publishers: [],modules: []}
  values.each_with_object(new_h) do |h, result| 
    result[:publishers] << {name: h["publisher_name"]}
    result[:modules] << h.slice("mn","mid")
  end
end