My respect to community!
I have deep nested hash and I want to transform all values of specific key provided. Something like deep transform values if key == :something
Example of hash:
{:id=>"11ed35b8e53c442ea210c39d6f24bddf",
:createdAt=>"2022-09-16T12:12:55.454Z",
:updatedAt=>"2022-09-16T12:12:55.454Z",
:status=>"ACTIVE",
:description=>"test",
:goals=>
[{:Definitions=>[],
:text=>"Follows Action Plan Appropriately, Worse or Warning Symptoms",
:status=>"ACTIVE",
:Definitions=>[{:text=>"Search for relics", :status=>"INACTIVE", :id=>"11ec1fc4bd36f876963867013cee2799"}],
:id=>"11e818be2f0157329c76634ee23c1d8f"}],
:healthConcernDefinitions=>[]}
I want to transform all values of all keys :status
Result must be:
{:id=>"11ed35b8e53c442ea210c39d6f24bddf",
:createdAt=>"2022-09-16T12:12:55.454Z",
:updatedAt=>"2022-09-16T12:12:55.454Z",
:status=>"TRANSFORMED",
:description=>"test",
:goals=>
[{:Definitions=>[],
:text=>"Follows Action Plan Appropriately, Worse or Warning Symptoms",
:status=>"TRANSFORMED",
:Definitions=>[{:text=>"Search for relics", :status=>"TRANSFORMED", :id=>"11ec1fc4bd36f876963867013cee2799"}],
:id=>"11e818be2f0157329c76634ee23c1d8f"}],
:healthConcernDefinitions=>[]}
I have a couple solutions First one:
hash_to_json = hash.to_json.gsub(/"ACTIVE"|"INACTIVE"/, '"TRANSFORMED"')
JSON.parse(hash_to_json)
Second one:
hash.deep_transform_values { |v| (v == 'ACTIVE' || v == 'INACTIVE') ? 'TRANSFORMED' : v }
Both solutions are working but I do not like to match values, I want to match only specific key and change it all over the hash, somting like:
hash.deep_transform_keys { |k, v| v = 'TRANSFORMED' if k == :status }
Thanks a lot!!!
We could implement a conditional overwrite of a key using an implementation akin to
deep_transform_keys.While this does not take a block format (as shown in your post), that did not seems to be necessary based on your use case. Instead this will simply overwrite the value of any key (nested at any level) contained in the original (
object) that is also contained inother_h.To call this in your case