在Ruby中合并嵌套的哈希数组

时间:2019-07-11 14:02:14

标签: ruby-on-rails ruby hash merge

在示例代码nameA和nameB中,与common_count比较时缺少几个日期。

因此,预期的输出哈希值必须存在缺少的日期,值将为零

谢谢。


    "common_count"=>[
         {20190704=>0}, {20190705=>0}, {20190706=>0}, {20190707=>0},               
         {20190708=>0}, {20190709=>0}, {20190710=>0}, {20190711=>0}
        ]
   }

   {

    "nameA"=>[
         {20190704=>10} {20190706=>50}, {20190707=>10},               
         {20190708=>0}, {20190709=>10}, {20190710=>0}, {20190711=>40}
        ],

   "nameB"=>[
         {20190704=>30}, {20190707=>20},               
         {20190708=>3}, {20190709=>5}, {20190710=>0}, {20190711=>20}
        ], ..... etc
   }

   "nameA"=>[
         {20190704=>10}, {20190705=>0}, {20190706=>50}, {20190707=>10},               
         {20190708=>0}, {20190709=>10}, {20190710=>0}, {20190711=>40}
        ],

   "nameB"=>[
         {20190704=>30},{20190705=>0}, {20190706=>0} {20190707=>20},               
         {20190708=>3}, {20190709=>5}, {20190710=>0}, {20190711=>20}
        ],...etc
   }

2 个答案:

答案 0 :(得分:1)

您可以简单地:

entries = {
  "common_count"=>[
   {"20190704"=>0}, {"20190705"=>0}, {"20190706"=>0}, {"20190707"=>0},               
   {"20190708"=>0}, {"20190709"=>0}, {"20190710"=>0}, {"20190711"=>0}
  ],
  "nameA"=>[
   {"20190704"=>10}, {"20190706"=>50}, {"20190707"=>10},               
   {"20190708"=>0}, {"20190709"=>10}, {"20190710"=>0}, {"20190711"=>40}
 ],
 "nameB"=>[
   {"20190704"=>30}, {"20190707"=>20},               
   {"20190708"=>3}, {"20190709"=>5}, {"20190710"=>0}, {"20190711"=>20}
 ]
}

default = entries.delete("common_count")
default_map = default.inject(:merge)

merged_entries = entries.map do |nameKey, value|
  value_map = value.inject(:merge)
  merged_value_map = default_map.merge(value_map)
  merged_value = merged_value_map.map { |k, v| {k => v} }

  {nameKey => merged_value}
end.inject(:merge)

请注意,为了合并哈希的内容,我必须将哈希数组转换为单个哈希。然后,我将哈希结果还原为哈希数组。

答案 1 :(得分:0)

如果您输入以下内容,

common_count = [{"20190704"=>0}, {"20190705"=>0}, {"20190706"=>0}, {"20190707"=>0}, {"20190708"=>0}, {"20190709"=>0}, {"20190710"=>0}, {"20190711"=>0}]

nameA = [{"20190704"=>10}, {"20190706"=>50}, {"20190707"=>10}, {"20190708"=>0}, {"20190709"=>10}, {"20190710"=>0}, {"20190711"=>40}]

nameB = [{"20190704"=>30}, {"20190707"=>20}, {"20190708"=>3}, {"20190709"=>5}, {"20190710"=>0}, {"20190711"=>20}]

您可以运行以下命令来添加common_count中缺少的密钥,

[nameA, nameB].each do |arr|
  (common_count.map(&:keys).flatten - arr.map(&:keys).flatten).each do |missing|
    arr.push({missing => 0})
  end
end