如何将嵌套Hash转换为单个Hash数组?
解决方案:将嵌套Hash转换为平铺Hash数组
没问题,用Ruby来处理这个转换非常直观,我给你两种实现方式,一种是分步循环的易懂版,另一种是更简洁的链式调用版:
分步循环实现(易读性高)
先定义你的原始数据:
original_data = {"2018-05-16"=>{ "ABCD"=>{929119=>0.14174555, 338296=>0.13858019, 332058=>0.13680765, 449614=>0.13679536}}}
然后通过三层循环逐层解析嵌套结构,把每个维度的字段提取出来拼成新的Hash:
result = [] # 第一层遍历日期 original_data.each do |target_date, locations| # 第二层遍历每个日期下的地点 locations.each do |location, ids_values| # 第三层遍历每个地点下的id和数值 ids_values.each do |id, value| result << { target_date: target_date, location: location, id: id, value: value } end end end # 输出结果 puts result.inspect
链式调用实现(简洁版)
如果喜欢更紧凑的写法,可以用flat_map和map的组合,自动展开嵌套数组:
original_data = {"2018-05-16"=>{ "ABCD"=>{929119=>0.14174555, 338296=>0.13858019, 332058=>0.13680765, 449614=>0.13679536}}} result = original_data.flat_map do |target_date, locations| locations.flat_map do |location, ids_values| ids_values.map do |id, value| { target_date: target_date, location: location, id: id, value: value } end end end puts result.inspect
两种方式最终都会输出你想要的平铺Hash数组:
[ {:target_date=>"2018-05-16", :location=>"ABCD", :id=>929119, :value=>0.14174555}, {:target_date=>"2018-05-16", :location=>"ABCD", :id=>338296, :value=>0.13858019}, {:target_date=>"2018-05-16", :location=>"ABCD", :id=>332058, :value=>0.13680765}, {:target_date=>"2018-05-16", :location=>"ABCD", :id=>449614, :value=>0.13679536} ]
内容的提问来源于stack exchange,提问作者user3186276
相关产品推荐
相关产品推荐

