简体   繁体   English

Ruby — 使用现有数组中的自定义键和值创建 hash

[英]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 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=>"Sincere@april.biz",
  :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). (还有4个人)。 I only need 2 keys and the new hash should look something like this我只需要 2 把钥匙,新的 hash 应该看起来像这样

    ideal_hash = {
          :full_name => ["Leanne Graham", "another name", "another name", "etc"]
          :email => ["Sincere@april.biz", "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.我尝试从 hash 中获取值并使用一组键对其进行压缩,但问题是我只得到 2 个值而不是 4 个,因为只有 2 个键,我尝试使用 map 但它也不太有效。 please help请帮忙

I only need 2 keys.. :full_name and:email我只需要 2 把钥匙.. :full_name 和:email

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM