lives_a
lives_a

Reputation: 15

Ruby -- Create hash with custom keys and values from an existing array

I have a response from api as a parsed JSON which is an array of hashes, I need to create a new hash with custom keys and the values that I will take from that api response

    #array of hashes looks like this:
    [{:id=>1,
  :name=>"Leanne Graham",
  :username=>"Bret",
  :email=>"[email protected]",
  :address=>
   {:street=>"Kulas Light",
    :suite=>"Apt. 556",
    :city=>"Gwenborough",
    :zipcode=>"92998-3874",
    :geo=>{:lat=>"-37.3159", :lng=>"81.1496"}},
  :phone=>"1-770-736-8031 x56442",
  :website=>"hildegard.org",
  :company=>
   {:name=>"Romaguera-Crona", :catchPhrase=>"Multi-layered client-server neural-net", :bs=>"harness real-time e-markets"}}]

(and there are 4 more people). I only need 2 keys and the new hash should look something like this

    ideal_hash = {
          :full_name => ["Leanne Graham", "another name", "another name", "etc"]
          :email => ["[email protected]", "some email", "another one", "etc"]
       }

there are gonna be more values in array but just these two custom keys. I tried taking values from hash and zipping it with an array of keys but the problem is that I only get 2 values instead of 4 because there are only 2 keys, I tried to map but it didnt quite work either. please help

Upvotes: 1

Views: 277

Answers (1)

Jared Beck
Jared Beck

Reputation: 17538

I only need 2 keys .. :full_name and :email

input.each_with_object({full_name: [], email: []}) do |e, a|
  a[:full_name] << e[:name]
  a[:email] << e[:email]
end

Upvotes: 1

Related Questions