[英]Merge two hashes with arrays by the same key Ruby
I need some help with Ruby. 我需要Ruby的帮助。 I have two hashes parsed from JSON. 我有两个从JSON解析出来的哈希值。 I use this code to parse files: 我使用以下代码来解析文件:
document = JSON.load File.new("hosts.txt")
file = JSON.load File.new("admins.txt")
The result are two big hashes like that: 结果就是这样的两个大哈希值:
document={"total"=>13, "subtotal"=>13, "page"=>1, "per_page"=>20,
"search"=>nil, "sort"=>{"by"=>nil, "order"=>nil},
"results"=>[
{"ip"=>"10", "environment_id"=>7,
"medium_id"=>nil, "name"=>"one", "id"=>1},
{"ip"=>"15", "environment_id"=>7,
"medium_id"=>nil, "name"=>"two", "id"=>1},
{"ip"=>"10.5", "environment_id"=>6,
"medium_id"=>nil, "name"=>"four", "id"=>1}]}
file={"admins"=>[
{"name"=>"one", "surname"=>"Mark", "email"=>"mark@o.com"},
{"name"=>"two", "surname"=>"Adam", "email"=>"Adam@o.com"},
{"name"=>"four", "surname"=>"Ami", "email"=>"Ami@o.com"}]}
From the first hash I need only information from the results key, so I have done 从第一个哈希中,我只需要来自结果键的信息,因此我已经完成了
data = document["results"]
I've done the same for the second hash: 对于第二个哈希,我已经做了同样的事情:
people = file["admins"]
Now, when the "name" values are the same I want to move surname and email from the people array to data array and have another hash like this: 现在,当“名称”值相同时,我想将姓和电子邮件从人员数组移到数据数组,并使用另一个哈希,如下所示:
new = {"all_data"=>[
{"ip"=>"10", "environment_id"=>7, "medium_id"=>nil,
"name"=>"one", "id"=>1, "surname"=>"Mark", "email"=>"mark@o.com"},
{"ip"=>"15", "environment_id"=>7, "medium_id"=>nil,
"name"=>"two", "id"=>1, "surname"=>"Adam", "email"=>"Adam@o.com"},
{"ip"=>"10.5", "environment_id"=>6, "medium_id"=>nil,
"name"=>"four", "id"=>1, "surname"=>"Ami", "email"=>"Ami@o.com"}]}
Can you help me to do that and explain how it works? 您能帮我做到这一点并解释它如何工作吗?
personal_data = file['admins'].map(&:dup)
.group_by { |e| e.delete('name') }
the dup
/ delete
trick above is not necessary, since merge
below will be handled properly in any case, but it's here for the sake of semantic clarity. 上面的dup
/ delete
技巧不是必需的,因为在任何情况下都可以正确处理下面的merge
,但这是出于语义清晰的目的。
document['results'].map do |h|
h.merge(personal_data[h['name']].first) if personal_data[h['name']]
end
#⇒ [
# {"ip"=>"10", "environment_id"=>7, "medium_id"=>nil, "name"=>"one",
# "id"=>1, "surname"=>"Mark", "email"=>"mark@o.com"},
# {"ip"=>"15", "environment_id"=>7, "medium_id"=>nil, "name"=>"two",
# "id"=>1, "surname"=>"Adam", "email"=>"Adam@o.com"},
# {"ip"=>"10.5", "environment_id"=>6, "medium_id"=>nil, "name"=>"four",
# "id"=>1, "surname"=>"Ami", "email"=>"Ami@o.com"}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.