简体   繁体   English

在哈希数组中转换哈希哈希

[英]Convert hash of hash in array of hash

I need to modify a hash of hash and convert it in a hash of array. 我需要修改哈希的哈希并将其转换为数组的哈希。

I also need to add a new key value. 我还需要添加一个新的键值。

This is my current hash: 这是我当前的哈希值:

{ "132552" => {
           "name" => "Paul",
           "id" => 53
         },
"22478" => {
          "name" => "Peter",
           "id" => 55
        }
}

I expect the output to be like this: 我希望输出是这样的:

[
  {
      "person_id": "132552",
      "name" => "Paul",
      "id" => 53
   },
   {
      "person_id": "22478",
      "name" => "Peter",
      "id" => 55
   }
]

You could map with Enumerable#map to hash values merging ( Hash#merge ) the new pairs: 您可以使用Enumerable#map映射合并新对的哈希值( Hash#merge ):

original_hash.map { |k,v| v.merge({ "person_id" => k }) }
#=> [{"name"=>"Paul", "id"=>53, "person_id"=>"132552"}, {"name"=>"Peter", "id"=>55, "person_id"=>"22478"}]

Probably not the best solution but the following should work (considering h is your hash): 可能不是最好的解决方案,但以下方法应该起作用(考虑h是您的哈希):

@h.each do |key,value|
  value["person_id"] = key
end

@array = []

@h.each do |key, value|
  @array << value
end

This is a perfect fit for Enumerable#each_with_object . 这非常适合Enumerable#each_with_object

output = input.each_with_object([]) do |(person_id, values), array|
  array << values.merge("person_id" => person_id)
end

This method takes an arbitrary object for our initial state (here an array), iterate the collection (our hash) with a block. 该方法为初始状态(此处为数组)获取一个任意对象,并使用一个块对集合(我们的哈希)进行迭代。 The initial object is yield as second argument of the block. 初始对象是yield作为该块的第二个参数。 At each iteration we're populating the array as we want. 在每次迭代中,我们都会根据需要填充数组。 At the end of the block this object is returned, in output variable in my example. 在该块的末尾,在我的示例中的output变量中返回了该对象。

Note that in my example, I destructure the hash into (person_id, values) : each entry of an hash can be destructed as (key, values) into block/method arguments. 请注意,在我的示例中,我将哈希分解为(person_id, values) :哈希的每个条目都可以作为(key, values)分解为block / method参数。

Enumerable#each_with_object 可枚举的#each_with_object

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

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