【问题标题】:Ruby -- Create hash with custom keys and values from an existing arrayRuby -- 使用现有数组中的自定义键和值创建哈希
【发布时间】:2021-04-08 03:20:07
【问题描述】:

我有一个来自 api 的响应,它是一个已解析的 JSON,它是一个哈希数组,我需要使用自定义键和我将从该 api 响应中获取的值创建一个新的哈希

    #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 个键,新的哈希应该是这样的

    ideal_hash = {
          :full_name => ["Leanne Graham", "another name", "another name", "etc"]
          :email => ["Sincere@april.biz", "some email", "another one", "etc"]
       }

数组中会有更多的值,但只有这两个自定义键。 我尝试从哈希中获取值并使用键数组对其进行压缩,但问题是我只得到 2 个值而不是 4 个,因为只有 2 个键,我尝试映射,但它也不太有效。请帮忙

【问题讨论】:

    标签: ruby


    【解决方案1】:

    我只需要 2 个密钥 .. :full_name 和 :email

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-02
      • 1970-01-01
      • 2022-01-10
      • 2015-04-19
      • 1970-01-01
      • 2014-07-21
      • 2015-08-26
      • 2012-11-23
      相关资源
      最近更新 更多