简体   繁体   English

在特定的 position 将值添加到数组 hash ruby

[英]Adding values to array hash ruby at a specific position

I have a hash response object which looks like this:我有一个 hash 响应 object 看起来像这样:

jsonResponse = {:json=>{"reply"=>[{"person"=>"abc", "roll_no"=>"1234", "location"=>"loc1", "score"=>"1"}, {"person"=>"def", "roll_no"=>"1235", "location"=>"loc2", "score"=>"2"},{"person"=>"fgh", "roll_no"=>"1236", "location"=>"loc3", "score"=>"3"}]}, :status=>200}

I have to add one key value pair at a specific position to each of these reply array objects, so that the response transforms to something like this, to make it simpler for now, lets try adding a samke key value pair at a particular position:我必须在每个回复数组对象中添加一个特定 position 的键值对,以便响应转换为类似这样的东西,为了现在更简单,让我们尝试在特定的 position 添加一个 samke 键值对:

jsonResponse = {:json=>{"reply"=>[{"person"=>"abc", "roll_no"=>"1234","location"=>"loc1", "new_value => "new_result", "score"=>"1"}, {"person"=>"def", "roll_no"=>"1235", "location"=>"loc2","new_value => "new_result", "score"=>"2"},{"person"=>"fgh", "roll_no"=>"1236", "location"=>"loc3", "new_value => "new_result", "score"=>"3"}]}, :status=>200}

This is what I have tried,I run.each through jsonResponse:这是我尝试过的,我通过jsonResponse运行.each:

jsonResponse[:json]['reply'].each do |object|
               objectArray = object.to_a
               insert_at = objectArray.index(objectArray.assoc('score'))
               object = Hash[objectArray.insert(insert_at, ['new_value','new_result'])]
               print("\n\nTest\n\n")
               print object
      end
    print("\n\nFinal Response\n\n")
    print jsonResponse

The object which i am printing has the desired response but it does not get updated in the jsonResponse我正在打印的object具有所需的响应,但它没有在jsonResponse中更新

This is the output of the above code snippet:这是上面代码片段的output:


Test

{"person"=>"abc", "roll_no"=>"1234", "location"=>"loc1", "new_value"=>"new_result", "score"=>"1"}

Test

{"person"=>"def", "roll_no"=>"1235", "location"=>"loc2", "new_value"=>"new_result", "score"=>"2"}

Test

{"person"=>"fgh", "roll_no"=>"1236", "location"=>"loc3", "new_value"=>"new_result", "score"=>"3"}

Final Response

{:json=>{"reply"=>[{"person"=>"abc", "roll_no"=>"1234", "location"=>"loc1", "score"=>"1"}, {"person"=>"def", "roll_no"=>"1235", "location"=>"loc2", "score"=>"2"}, {"person"=>"fgh", "roll_no"=>"1236", "location"=>"loc3", "score"=>"3"}]}, :status=>200}

Q2. Q2。 Also as you can see from the code snippet the insert_at logic works in a way that it adds before the position we specify, for eg it adds before score key , is there a logic which i can write which adds to the position after the specified key and not before?此外,正如您从代码片段中看到的那样, insert_at逻辑的工作方式是在我们指定的 position 之前添加,例如它在score 键之前添加,是否有我可以编写的逻辑在指定键之后添加到 position而不是之前?

Appreciate the efforts by everyone感谢大家的努力

We are given three objects.我们得到了三个对象。

jsonResponse = {
  :json=>{
    "reply"=>[
      {"person"=>"abc", "roll_no"=>"1234", "location"=>"loc1", "score"=>"1"},
      {"person"=>"def", "roll_no"=>"1235", "location"=>"loc2", "score"=>"2"}, 
      {"person"=>"fgh", "roll_no"=>"1236", "location"=>"loc3", "score"=>"3"}
    ]
  },
  :status=>200
}

key_value_pair_to_add = { 'new_value'=>'new_result' }
key_to_precede = 'location'

We then modify jsonResponse as follows.然后我们修改jsonResponse如下。

keys_to_shift = jsonResponse[:json]['reply'][0].keys.
  drop_while { |k| k != key_to_precede }        
  #=> ["location", "score"]
jsonResponse[:json]['reply'].each do |h| 
  h.update('new_value'=>'new_result')
  keys_to_shift.each { |k| h.update(k=>h.delete(k)) }
end
jsonResponse
  #=> {
  #     :json=>{
  #       "reply"=>[
  #         {"person"=>"abc", "roll_no"=>"1234", "new_value"=>"new_result",
  #          "location"=>"loc1", "score"=>"1"},
  #         {"person"=>"def", "roll_no"=>"1235", "new_value"=>"new_result",
  #          "location"=>"loc2", "score"=>"2"},
  #         {"person"=>"fgh", "roll_no"=>"1236", "new_value"=>"new_result",
  #          "location"=>"loc3", "score"=>"3"}
  #       ]
  #     },
  #     :status=>200
  #   }

See Hash#update (aka merge! ) and Hash#delete .请参阅Hash#update (又名merge! )和Hash#delete

h.delete('location')

removes the key-value pair 'location'=>'locX' from h and returns locX , after whichh中删除键值对'location'=>'locX'并返回locX ,之后

h.update('location'=>'locX')

returns that key-value pair to the end of the hash.将该键值对返回到 hash 的末尾。 This is repeated for each key in keys_to_shift .这对keys_to_shift中的每个键重复。

Give a simple example:举一个简单的例子:

# define order 
order = [:first, :second, :third]
# the hash you want to order by
json = { :third=>"3", :second=>2, :first=>1 }

result = json.sort_by { |k, _| order.index(k) }.to_h

then result will be {:first=>1, :second=>2, :third=>"3"}那么结果将是{:first=>1, :second=>2, :third=>"3"}

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

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