简体   繁体   English

Rails:如何更新数组中的哈希

[英]Rails: How to update the hash in an array

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? 我是根据遇到的其他一些问题(例如这个问题)构建的。 如何在Ruby中遍历数组时修改数组?

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: 要访问Hash结构中的对象,可以使用符号或字符串作为选择器,如下所示:

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. 您提供的代码中存储的对象已经是ruby代码,哈希键只是字符串而不是符号。

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. 您也不想将form_fields变量更新为地图的结果,因为这将覆盖您的数组,并且仅保留数组中的最后一个元素。

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=>{ ... }}]

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

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