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}, ...]
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.
If using Rails, let's use Hash#slice
, prettier :
b_and_c_array = array.map{|a| a.slice(:b, :c) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With