Collect Values from an Array of Hashes

Get a value from an array of hashes in ruby

The select statement will return all the hashes with the key 13.

If you already know which hash has the key then the below code will give u the answer.

ary[1][13]

However if you are not sure which of your hashes in the array has the value, then you could do the following:

values = ary.map{|h| h[13]}.compact

Values will have the value of key 13 from all the hashes which has the key 13.

Collect specific values from an array of hashes

A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type.

Of course, a value can be any object - string, method, nil, number, object. So, only after create, we can know that is saved in our hash. For this reason when trying to get all key:

data.keys # => ["etag", "items"]

There is no any nested key. So finding value by missing key return nil.

To select all videoId you must do something like this:

data["items"].map { |item| item["snippet"]["resourceId"]["videoId"] }.compact

Also, you can update Hash class as there:

class Hash
def deep_find(key, object=self, found=nil)
if object.respond_to?(:key?) && object.key?(key)
return object[key]
elsif object.is_a? Enumerable
object.find { |*a| found = deep_find(key, a.last) }
return found
end
end
end

And then run

data["items"].map { |item| item.deep_find('videoId') }

That method avoids the error when the json will have a variable structure.

Get an array of the values of a key from an array of hashes?

You can do it yourself:

class Array
def get_values(key)
self.map{|x| x[key]}
end
end

Then you can do this:

a.get_values :a
#=> ["a", "b", "c"]

Is there a clean way to access hash values in array of hashes?

If you don't mind monkey-patching, you can go pluck yourself:

arr = [{ id: 1, body: 'foo'}, { id: 2, body: 'bar' }, { id: 3, body: 'foobar' }]

class Array
def pluck(key)
map { |h| h[key] }
end
end

arr.pluck(:id)
=> [1, 2, 3]
arr.pluck(:body)
=> ["foo", "bar", "foobar"]

Furthermore, it looks like someone has already generalised this for Enumerables, and someone else for a more general solution.

Return specific values from array of hashes - JSON

yes, at the end, I find the solution. res is an array and there are multiple hashes in this array, As I'm getting this from Google Places API, so if someone wants to access the name, latitude, longitude, place_id of nearby restaurants he can do it easily by .Map by the following code.

resturants =res.map { |a| {id: a.place_id ,  name: a.name , lat: a.lat, lng: a.lng , icon: a.icon}}
json_response "Successfully retrive data" , true, {Resturant: resturants }, :ok

How to extract hashes from an array of hashes based on array value

check.flat_map{|c| input_hash.select{|aa| aa["id"] == c}}.map{|a| a["name"]}.join(", ")
=> "george, nancy"

or

input_hash.select{|h| h["name"] if check.include? h["id"]}.map{|aa| aa["name"]}.join(", ")
=> "george, nancy"

How to search for a hash key value in an array of hashes

find returns a hash in your case, just pass the key :place to get the value:

hash = array.find {|x| x[:name] == "John"}
return if hash.nil?
hash[:place]

Regarding the query about mixed values, I just tried it in IRB and it worked fine.

2.7.0 :014 > array = [
2.7.0 :015 > {:name => "Bob" , :age => 27 , :place => "A"} ,
2.7.0 :016 > {:name => "John" , :age => 50 , :place => "B"} ,
2.7.0 :017 > {:name => "Alex" , :age => 80 , :place => "C"}
2.7.0 :018 > ]
2.7.0 :019 > array.find {|x| x[:name] == "John"}
=> {:name=>"John", :age=>50, :place=>"B"}

How to iterate over an array of hashes in Ruby and return all of the values of a specific key in a string

You can use Enumerable#map for this:

p foods.map { |f| f[:name] }

The code you tried to use did not produce any output or create any objects, and it was not necessary to use a second loop to access a single element of a hash.

How to get all values for a key from an array of hashes?

I have tested this and it seem to work as expected!

arrOfHashes.map{|i| i["name"]}.sample(1)


Related Topics



Leave a reply



Submit