Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object from nested hash depending on key value

Tags:

ruby

I get a google api response and have a the following hash:

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"}}

I need to get the value of displayName from the nested hash where "isBroadcaster"=>"true". (In this case the displayName is John Doe). I just can't get my head around this problem and would appreciate some help. Thank you in advance.

like image 279
Thomas Avatar asked Aug 16 '26 12:08

Thomas


1 Answers

Assuming that there will be only 1 broadcaster.

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

For multiple broadcasters, this:

api_response.each_with_object([]) do |(_, hash), array|
  array << hash['person']['displayName'] if hash['isBroadcaster'] == 'true'
end
like image 101
SHS Avatar answered Aug 18 '26 04:08

SHS