简体   繁体   English

在哈希数组中查找值以创建新的哈希数组

[英]Find values in array of hashes to create new array of hashes

I have some data returned from an api which I've parsed down to this: 我有一些从api返回的数据,我已经将其解析为:

[{:a=>value1, :b=>value2, :c=>value3, :d=>value4}, {:a=>value5, :b=>value6, :c=>value7, :d=>value8},{:a=>value9, :b=>value10, :c=>value11, :d=>value12}, ...]

How can I create a new array of hashes with the keys AND values of b and c , given key = b and key = c ? 在给定key = bkey = c如何使用bc键和值创建一个新的哈希数组? I want to pass the key and return the value and maintain the key. 我想传递密钥并返回值并维护密钥。 So I want to end up with: 因此,我想得出以下结论:

[{:b=>value2, :c=>value3}, {:b=>value6, :c=>value7}, {:b=>value10, :c=>value11}, ...]

Pure ruby 纯红宝石

array = [{:a=>'value1', :b=>'value2', :c=>'value3', :d=>'value4'}, {:a=>'value1', :b=>'value2', :c=>'value3', :d=>'value4'}]

b_and_c_array = array.map{|a| a.select{|k, _| [:b, :c].include?(k)} }

We take each hash using the map method that will return a result array. 我们使用map方法获取每个哈希值,该方法将返回结果数组。 For each hash, we select only [:b, :c] keys. 对于每个哈希,我们仅选择[:b, :c]键。 You can add more inside it. 您可以在其中添加更多内容。

Rails 滑轨

If using Rails, let's use Hash#slice , prettier : 如果使用Rails,请使用更漂亮的Hash#slice

b_and_c_array = array.map{|a| a.slice(:b, :c) }

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

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