Arrays 将嵌套哈希转换为单个哈希
我想将此示例数据转换为:Arrays 将嵌套哈希转换为单个哈希,arrays,ruby,hash,nested,Arrays,Ruby,Hash,Nested,我想将此示例数据转换为: {"2018-05-16"=>{ "ABCD"=>{929119=>0.14174555, 338296=>0.13858019, 332058=>0.13680765, 449614=>0.13679536}}} 在这个散列数组中: [ {"target_date"=>"2018-05-16", "location"=>"ABCD", "id"=>929119, "value"=>0.1417455
{"2018-05-16"=>{
"ABCD"=>{929119=>0.14174555, 338296=>0.13858019, 332058=>0.13680765, 449614=>0.13679536}}}
在这个散列数组中:
[
{"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}
]
另一种方法——可以概括——如下
对于此散列,将返回以下数组
[{"target_date"=>"2018-05-16", "location"=>"ABCD", "id"=>92, "value"=>0.14},
{"target_date"=>"2018-05-16", "location"=>"ABCD", "id"=>44, "value"=>0.13},
{"target_date"=>"2018-05-16", "location"=>"EFGH", "id"=>12, "value"=>0.24},
{"target_date"=>"2018-05-16", "location"=>"EFGH", "id"=>34, "value"=>0.23},
{"target_date"=>"2018-05-17", "location"=>"ABCD", "id"=>52, "value"=>0.34},
{"target_date"=>"2018-05-17", "location"=>"ABCD", "id"=>34, "value"=>0.33},
{"target_date"=>"2018-05-17", "location"=>"EFGH", "id"=>42, "value"=>0.44},
{"target_date"=>"2018-05-17", "location"=>"EFGH", "id"=>74, "value"=>0.43}]
你的问题是什么?这个问题是隐含的,我想对于这个论坛的聪明人来说,不需要明确。如果没有,那么我如何实现上述目标?sawa的意思是:“您为解决此问题而编写的代码的具体问题是什么?”。现在看来,您希望我们为您编写代码,因此最好包括您编写的代码、收到的错误消息,并解释如何将输入转换为输出的规则,而不是只给出一个示例。明白。我已经解决了这个问题。感谢所有人的帮助,代码或其他。
h.each_with_object([]) do |(k0,v0),arr|
v0.each do |k1,v1|
v1.each.map do |k2,v2|
arr << { "target_date"=>k0, "location"=>k1, "id"=>k2, "value"=>v2 }
end
end
end
#=> <same as for first method>
{ "2018-05-16"=>{ "ABCD"=>{ 92=>0.14, 44=>0.13 }, "EFGH"=>{ 12=>0.24, 34=>0.23 } },
"2018-05-17"=>{ "ABCD"=>{ 52=>0.34, 34=>0.33 }, "EFGH"=>{ 42=>0.44, 74=>0.43 } } }
[{"target_date"=>"2018-05-16", "location"=>"ABCD", "id"=>92, "value"=>0.14},
{"target_date"=>"2018-05-16", "location"=>"ABCD", "id"=>44, "value"=>0.13},
{"target_date"=>"2018-05-16", "location"=>"EFGH", "id"=>12, "value"=>0.24},
{"target_date"=>"2018-05-16", "location"=>"EFGH", "id"=>34, "value"=>0.23},
{"target_date"=>"2018-05-17", "location"=>"ABCD", "id"=>52, "value"=>0.34},
{"target_date"=>"2018-05-17", "location"=>"ABCD", "id"=>34, "value"=>0.33},
{"target_date"=>"2018-05-17", "location"=>"EFGH", "id"=>42, "value"=>0.44},
{"target_date"=>"2018-05-17", "location"=>"EFGH", "id"=>74, "value"=>0.43}]