0

How to update a hash from an array?

Sample Data

form_fields = [
{
  key: '1',
  properties: null
},
{
  key: '2',
  properties: {"options"=>[{"label"=>"Europe", "value"=>"europe"}, {"label"=>"North America", "type"=>"groupstart"}, {"label"=>"Canada", "value"=>"canada"}, {"label"=>"USA", "value"=>"usa"}, {"label"=>"", "type"=>"groupend"}]}
}
]

Code I have so far

      form_fields = form_fields.map {
        |field| {
          field.properties = field.properties ? JSON.parse(field.properties) : {}
      }

I built this based on some other questions I came across such as this one How do I modify an array while I am iterating over it in Ruby?

Community
  • 1
  • 1
Suthan Bala
  • 3,209
  • 5
  • 34
  • 59

1 Answers1

2

The syntax for the map is very close to what you already have, the correct syntax would be like this:

form_fields = form_fields.map { 
    |field|
        ...
}

To access a object in the Hash structure you would use the symbol, or string as the selector, like this:

field[:properties]
field[:properties]["options"]

The code you have in your map, does not really make sense. The object stored in the code you provided is already ruby code, the hash keys is just strings instead of symbols.

You do also not want to update your form_fields variable to the result of your map, since that will overwrite your array, and only keep the last element in the array.

I believe what you want is something like this:

form_fields.map { |field| 
    field[:properties] = field[:properties] ? field[:properties] : {}
}

That will turn your array from:

[{:key=>"1", :properties=>nil}, {:key=>"2", :properties=>{ ... }}]

to:

[{:key=>"1", :properties=>{}}, {:key=>"2", :properties=>{ ... }}]
Lasse Sviland
  • 1,479
  • 11
  • 23