鉴于此数组:
[[{"RepCode"=>"AL20", "ID"=>"eae71dff-3796-4c61-956e-a75a00b01a7b", "Name"=>"Schuh, Eddy", "Folios"=>[]}],
[{"RepCode"=>"ABNX", "ID"=>"637e9117-ed03-45ef-8950-a7220087ee9a", "Name"=>"Eckerson, Kathy", "Folios" => [{"ID"=>"d0cda2be-c142-47d1-9a81-a76c0eea2765"}],
[{"RepCode"=>"ABCD", "ID"=>"637e9117-ed03-45ef-8950-a234902038", "Name"=>"Sarah, Barber", "Folios" => [{"ID"=>"46aafe31-f686-49e2-9d58-c694ea55c14f"}]]
我需要返回与<{1}}键的给定ID匹配的 ONE 数组
Folio
返回:
correct_manager = managers.detect do |manager|
manager.first["Folios"].map { |f| f["ID"] == "d0cda2be-c142-47d1-9a81-a76c0eea2765" }
end
我希望它返回
{"RepCode"=>"AL20", "ID"=>"eae71dff-3796-4c61-956e-a75a00b01a7b", "Name"=>"Schuh, Eddy", "Folios"=>[]}
因为ID在检测方法中匹配。
如何返回与传入的id匹配的一个数组?
答案 0 :(得分:2)
您可以使用Enumerable #find
correct_manager = managers.find do |manager|
folios = manager.first["Folios"][0] || {}
folios["ID"] == "d0cda2be-c142-47d1-9a81-a76c0eea2765"
end
答案 1 :(得分:1)
def doit(managers, val)
managers.find { |(h)| h["Folios"] == ["ID"=>val] }
end
managers = [
[{ "RepCode"=>"AL20", "Folios"=>[] }],
[{ "RepCode"=>"ABNX", "Folios"=>[{ "ID"=>"d0cda2be-c142-47d1-9a81" }] }],
[{ "RepCode"=>"ABCD", "Folios"=>[{ "ID"=>"46aafe31-f686-49e2-9d58" }] }]
]
doit(managers, "d0cda2be-c142-47d1-9a81")
# => [{"RepCode"=>"ABNX", "Folios"=>[{"ID"=>"d0cda2be-c142-47d1-9a81"}]}]
答案 2 :(得分:1)
首先让我们正确格式化您的数据:
managers = [
[ {"RepCode"=>"AL20", "ID"=>"eae71dff-3796-4c61-956e-a75a00b01a7b", "Name"=>"Schuh, Eddy", "Folios"=>[] } ],
[ {"RepCode"=>"ABNX", "ID"=>"637e9117-ed03-45ef-8950-a7220087ee9a", "Name"=>"Eckerson, Kathy", "Folios" => [{"ID"=>"d0cda2be-c142-47d1-9a81-a76c0eea2765"}] } ],
[ {"RepCode"=>"ABCD", "ID"=>"637e9117-ed03-45ef-8950-a234902038", "Name"=>"Sarah, Barber", "Folios" => [{"ID"=>"46aafe31-f686-49e2-9d58-c694ea55c14f"}] } ]
]
target_id = 'd0cda2be-c142-47d1-9a81-a76c0eea2765'
managers.flatten.find{|k,_v| k['Folios'].any?{|f| f.key?('ID') && f['ID'] == target_id}}