【问题标题】:Rails: How to update the hash in an arrayRails:如何更新数组中的哈希
【发布时间】:2017-08-12 04:35:17
【问题描述】:

如何更新数组中的哈希?

样本数据

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"}]}
}
]

我目前拥有的代码

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

我根据遇到的其他一些问题构建了这个,例如How do I modify an array while I am iterating over it in Ruby?

【问题讨论】:

  • 预期结果是什么?
  • form_fields 包含一个 JSON properties 属性

标签: ruby-on-rails ruby-on-rails-5


【解决方案1】:

地图的语法与你已有的非常接近,正确的语法应该是这样的:

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

要访问 Hash 结构中的对象,您可以使用符号或字符串作为选择器,如下所示:

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

地图中的代码实际上没有意义。您提供的代码中存储的对象已经是 ruby​​ 代码,哈希键只是字符串而不是符号。

您也不希望将 form_fields 变量更新为地图的结果,因为这会覆盖您的数组,并且只保留数组中的最后一个元素。

我相信你想要的是这样的:

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

这将使您的数组从:

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

到:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-28
    • 2014-05-11
    • 1970-01-01
    • 2011-04-20
    相关资源
    最近更新 更多