我想合并以下两个哈希数组(arr1
和arr2
)。这样做的最佳方式是什么?
要对密钥:_id
的值进行聚合。
arr1 = [
{
"_id": {
"year": 2017,
"month": 3
},
"enroll_count": 2267
},
{
"_id": {
"year": 2017,
"month": 2
},
"enroll_count": 1829
}
]
arr2 = [
{
"_id": {
"year": 2017,
"month": 3
},
"other_count": 2
},
{
"_id": {
"year": 2017,
"month": 2
},
"other_count": 3
}
]
期望的结果
[
{
"_id": {
"year": 2017,
"month": 3
},
"enrolled_count": 2267,
"other_count": 2
},
{
"_id": {
"year": 2017,
"month": 2
},
"enrolled_count": 1829
"other_count": 3
}
]
我尝试使用Hash#merge
,但没有成功。
答案 0 :(得分:0)
(arr1+arr2).each_with_object({}) {|g,h| h.update(g[:_id]=>g) {|_,o,n| o.merge(n)}}.values
#=> [{:_id=>{:year=>2017, :month=>3}, :enroll_count=>2267, :other_count=>2},
# {:_id=>{:year=>2017, :month=>2}, :enroll_count=>1829, :other_count=>3}]
请注意,在执行.values
之前,我们有
(arr1+arr2).each_with_object({}) {|g,h| h.update(g[:_id]=>g) {|_,o,n| o.merge(n)}}
#=> {{:year=>2017, :month=>3}=>{:_id=>{:year=>2017, :month=>3},
# :enroll_count=>2267,
# :other_count=>2
# },
# {:year=>2017, :month=>2}=>{:_id=>{:year=>2017, :month=>2},
# :enroll_count=>1829,
# :other_count=>3
# }
# }
这使用Hash#update(aka merge!
)的形式,它使用块({ |_,o,n| o.merge(n) }
)来确定两者中存在的键值(:_id
)哈希被合并。有关该值解析块中三个块变量值的解释,请参阅doc。
此方法不要求要组合的哈希在各自的数组中具有相同的索引。