[英]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=>"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"}}]
(還有4個人)。 我只需要 2 把鑰匙,新的 hash 應該看起來像這樣
ideal_hash = {
:full_name => ["Leanne Graham", "another name", "another name", "etc"]
:email => ["Sincere@april.biz", "some email", "another one", "etc"]
}
數組中會有更多的值,但只有這兩個自定義鍵。 我嘗試從 hash 中獲取值並使用一組鍵對其進行壓縮,但問題是我只得到 2 個值而不是 4 個,因為只有 2 個鍵,我嘗試使用 map 但它也不太有效。 請幫忙
我只需要 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.