从包含特定键的哈希数组中删除哈希

时间:2017-05-12 14:06:39

标签: ruby recursion ruby-hash

我有这个哈希:

{ "car": [
  { "key": 'removeMe1', "name": 'ok' },
  { "key": 'dontRemoveMe1', "surname": 'ok' },
  { "key": 'dontRemoveMe2',
    "array": [
      { "trucks": [
        { "key": 'removeMe2', "name": 'my_profile_name' }
      ] },
      { "trucks": [
        { "key": 'dontRemoveMe3', "name": '34' },
        { "key": 'removeMe3', "surname": '5324' }
      ]}
  ] }
]}

我想删除包含removeMe*

的哈希
{ "car": [
  { "key": 'dontRemoveMe1', "surname": 'ok' },
  { "key": 'dontRemoveMe2',
    "array": [
      { "trucks": [
        { "key": 'dontRemoveMe3', "name": '34' }
      ] }
  ] }
]}

如果我做的话,我在第一级取得成功

my_hash.delete_if { |h| ['removeMe1'].exclude?(h['key']) }

但我不知道如何为嵌套级别做这件事。

1 个答案:

答案 0 :(得分:3)

def delete_by_key(data)
  data.each do |k, v|
    if Array === v
      v.each{ |i| delete_by_key(i) }
      v.delete_if { |i| i[:key] && i[:key]["removeMe"] or i.empty? }
      data.delete(k) if v.empty?
    end
  end
end

结果如下

data = { 
  "car": [
    { "key": 'removeMe1', "name": 'ok' },
    { "key": 'dontRemoveMe1', "surname": 'ok' },
    { "key": 'dontRemoveMe2',
      "array": [
        { "trucks": [
          { "key": 'removeMe2', "name": 'my_profile_name' }
        ] },
        { "trucks": [
          { "key": 'dontRemoveMe3', "name": '34' },
          { "key": 'removeMe3', "surname": '5324' }
        ]}
    ] 
  }
]}

delete_by_key(data)
#=> {:car=>[{:key=>"dontRemoveMe1", :surname=>"ok"}, {:key=>"dontRemoveMe2", :array=>[{:trucks=>[{:key=>"dontRemoveMe3", :name=>"34"}]}]}]}