Ruby:重命名哈希数组中的键?

时间:2013-07-21 14:08:29

标签: ruby arrays hash key rename

如何在MongoDB文档数组中将_id键重命名为id

所以,我想这样做:

[{"_id"=>"1", "name"=>"Matt"}, {"_id"=>"2", "name"=>"John"}, ...]

进入这个:

[{"id"=>"1", "name"=>"Matt"}, {"id"=>"2", "name"=>"John"}, ...]

2 个答案:

答案 0 :(得分:3)

我找到了完整的解决方案。

mongo_db['users'].find().to_a.each do |u|
  u['id'] = u.delete '_id'
end.to_json

答案 1 :(得分:0)

ar = [{"_id"=>"1", "name"=>"Matt"}, {"_id"=>"2", "name"=>"John"}]
ar.each{|h| h.store('id',h.delete('_id'))}
ar # => [{"name"=>"Matt", "id"=>"1"}, {"name"=>"John", "id"=>"2"}]

如果您不想修改原始数组,请执行以下操作:

ar = [{"_id"=>"1", "name"=>"Matt"}, {"_id"=>"2", "name"=>"John"}]
ar.map{|h| {"id"=>h['_id'], "name"=>h['name']} }
# => [{"id"=>"1", "name"=>"Matt"}, {"id"=>"2", "name"=>"John"}]