4

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}, ...]

1 Answer 1

8

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) }
Sign up to request clarification or add additional context in comments.

3 Comments

Wow! Worked like a charm. I'm trying to get lat and lng info from api data into json for google maps api rendering. This method lets me select the lat and lng values as [{lat=>value1, lng=>value2},...] but I need [{lat:value1, lng:value2}]. Any idea about this? Appreciate it.
What do you mean? The api sends you malformed json back?
I got it. Just needed to convert results to_json. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.