嵌套哈希中的对象,具体取决于键值



我得到一个谷歌 api 响应,并有一个以下哈希:

api_response = {"0"=>{"id"=>"xxx.id.google.com^xxx", "hasMicrophone"=>"true", "hasCamera"=>"true", "hasAppEnabled"=>"false", "isBroadcaster"=>"false", "isInBroadcast"=>"true", "displayIndex"=>"0", "person"=>{"id"=>"xxx", "displayName"=>"Foo Bar", "image"=>{"url"=>".../s96-c/photo.jpg"}, "fa"=>"false"}, "locale"=>"en", "fa"=>"false"}, "1"=>{"id"=>"xxx.id.google.com^3772edb7c0", "hasMicrophone"=>"true", "hasCamera"=>"true", "hasAppEnabled"=>"false", "isBroadcaster"=>"false", "isInBroadcast"=>"true", "displayIndex"=>"1", "person"=>{"id"=>"xxx", "displayName"=>"Bar Foo", "image"=>{"url"=>".../s96-c/photo.jpg"}, "fa"=>"false"}, "locale"=>"en", "fa"=>"false"}, "2"=>{"id"=>"xxx.id.google.com^98ebb1f610", "hasMicrophone"=>"true", "hasCamera"=>"true", "hasAppEnabled"=>"true", "isBroadcaster"=>"true", "isInBroadcast"=>"true", "displayIndex"=>"2", "person"=>{"id"=>"xxx", "displayName"=>"John Doe", "image"=>{"url"=>".../s96-c/photo.jpg"}, "fa"=>"false"}, "locale"=>"en", "fa"=>"false"}}

我需要从嵌套哈希中获取displayName的值,其中"isBroadcaster"=>"true".(在本例中,displayNameJohn Doe )。我只是无法解决这个问题,并希望得到一些帮助。提前谢谢你。

假设只有 1 个广播公司。

api_response.each do |_, hash|
  break hash['person']['displayName'] if hash['isBroadcaster'] == 'true'
end

对于多个广播公司,这:

api_response.each_with_object([]) do |(_, hash), array|
  array << hash['person']['displayName'] if hash['isBroadcaster'] == 'true'
end

你必须做

# get all broadcasters
api_response.map do |_, hash| 
  hash["person"]["displayName"] if hash["isBroadcaster"] == "true"
end.compact
# if you want the first broadcaster, then
broad_caster = api_response.find do |_, hash|
  hash["isBroadcaster"] == "true"
end
broad_caster && broad_caster.last["person"]["displayName"]

您可以组合selectEnumerable中的map以获得第一个匹配项。

display_name = api_response.select { |k,v|
  v['isBroadcaster'] == 'true'
}.map { |k,v|
  v['person']['displayName']
}.first

既然你不关心键,怎么样:

broadcaster = api_response.values.detect{|h| h['isBroadcaster'] == 'true'}
broadcaster ? broadcaster['person']['displayName'] : nil

或者这也行得通:

api_response.values.detect(->{{'person'=>{}}}){|h| h['isBroadcaster'] == 'true'}['person']['displayName']

然后它会找到第一个isBroadcaster,如果没有,它会返回nil

最新更新