ma11hew28
ma11hew28

Reputation: 126357

Ruby: Rename keys in array of hashes?

How do I rename the _id keys to id in an array of MongoDB documents?

So, I want to make this:

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

into this:

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

Upvotes: 2

Views: 3709

Answers (2)

Arup Rakshit
Arup Rakshit

Reputation: 118271

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

If you don't want to modify the original array do as below:

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

Upvotes: 5

ma11hew28
ma11hew28

Reputation: 126357

I found the complete solution.

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

Upvotes: 4

Related Questions