[英]Rails: How to update the hash in an array
如何從數組更新哈希?
樣本數據
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) : {}
}
我是根據遇到的其他一些問題(例如這個問題)構建的。 如何在Ruby中遍歷數組時修改數組?
地圖的語法與您已經擁有的語法非常接近,正確的語法應如下所示:
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=>{ ... }}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.