简体   繁体   English

在Ruby中将哈希数组映射到键控哈希

[英]Mapping an array of hashes to a keyed hash in Ruby

I have an array of hashes that looks like this: 我有一系列看起来像这样的哈希:

   array= [
      {
        "id"=> 101,
        "first_name"=> "xxx",
        "last_name"=> "G",
        "email"=> "xxx@yyyy.com",
        "phone_number"=> "555-555-5555"
      },
      {
        "id"=> 102,
        "first_name"=> "Jen",
        "last_name"=> "P",
        "email"=> "jen.p@example.com",
        "phone_number"=> "555-555-5555"
      }
    ]

I want to convert it to a hash that looks like this: 我想将其转换为如下所示的哈希:

   array = {
          "101"=> 
          {
            "first_name"=> "xxx",
            "last_name"=> "G",
            "email"=> "xxx@yyyy.com",
            "phone_number"=> "555-555-5555"
          },
          "102"=>
          {
            "first_name"=> "Jen",
            "last_name"=> "P",
            "email"=> "jen.p@example.com",
            "phone_number"=> "555-555-5555"
          }
       }

I have tried this but it does not work: 我已经尝试过了,但是没有用:

    array.each do |a|
      a.map{|x| x[:id]}
    end

How can I do this in Ruby? 如何在Ruby中执行此操作? I am looking at the map function, but not sure how to implement it in this case. 我正在查看map函数,但不确定在这种情况下如何实现它。 Please help! 请帮忙!

This works(desctructive): 这有效(说明性):

>> Hash[array.map { |x| [x.delete("id"), x] }]
=>{
    101=>{
        "first_name"=>"xxx",
        "last_name"=>"G",
        "email"=>"xxx@yyyy.com",
        "phone_number"=>"555-555-5555"
    },
    102=>{
        "first_name"=>"Jen",
        "last_name"=>"P",
        "email"=>"jen.p@example.com",
        "phone_number"=>"555-555-5555"
    }
}

Try this: 尝试这个:

array_h = Hash.new
array.each{|a| array_h[a["id"]] = a.reject{|e| e=='id' }}

#Output of array_h:
{
  101=>
    {
      "first_name"=>"xxx", 
      "last_name"=>"G", 
      "email"=>"xxx@yyyy.com", 
      "phone_number"=>"555-555-5555"
    }, 
  102=>
    {
      "first_name"=>"Jen", 
      "last_name"=>"P", 
      "email"=>"jen.p@example.com", 
      "phone_number"=>"555-555-5555"
    }
}

Note: This will not modify your original Array. 注意:这不会修改原始阵列。

Non-destructive variant (preserves array ) while removing "id" : 无损变体(保留array ),同时删除"id"

{}.tap { |h| array.each { |a| nh = a.dup; h[nh.delete('id')] = nh } }
# => {101=>{"first_name"=>"xxx", "last_name"=>"G", "email"=>"xxx@yyyy.com", "phone_number"=>"555-555-5555"}, 102=>{"first_name"=>"Jen", "last_name"=>"P", "email"=>"jen.p@example.com", "phone_number"=>"555-555-5555"}} 
array
# => [{"id"=>101, "first_name"=>"xxx", "last_name"=>"G", "email"=>"xxx@yyyy.com", "phone_number"=>"555-555-5555"}, {"id"=>102, "first_name"=>"Jen", "last_name"=>"P", "email"=>"jen.p@example.com", "phone_number"=>"555-555-5555"}] 

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

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