Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find values in array of hashes to create new array of hashes

I have some data returned from an api which I've parsed down to this:

[{:a=>value1, :b=>value2, :c=>value3, :d=>value4}, {:a=>value5, :b=>value6, :c=>value7, :d=>value8},{:a=>value9, :b=>value10, :c=>value11, :d=>value12}, ...]

How can I create a new array of hashes with the keys AND values of b and c, given key = b and key = c? I want to pass the key and return the value and maintain the key. So I want to end up with:

[{:b=>value2, :c=>value3}, {:b=>value6, :c=>value7}, {:b=>value10, :c=>value11}, ...]
like image 412
alw615 Avatar asked Feb 19 '23 12:02

alw615


1 Answers

Pure ruby

array = [{:a=>'value1', :b=>'value2', :c=>'value3', :d=>'value4'}, {:a=>'value1', :b=>'value2', :c=>'value3', :d=>'value4'}]

b_and_c_array = array.map{|a| a.select{|k, _| [:b, :c].include?(k)} }

We take each hash using the map method that will return a result array. For each hash, we select only [:b, :c] keys. You can add more inside it.

Rails

If using Rails, let's use Hash#slice, prettier :

b_and_c_array = array.map{|a| a.slice(:b, :c) }
like image 87
Anthony Alberto Avatar answered Apr 08 '23 21:04

Anthony Alberto