Crazy Coders
Crazy Coders

Reputation: 133

Ruby mongo - array map add another field

I have a MongoDB model like:

Posts: id, category, data[title, description, slug..]  

I was adding my data to my_array but now I need to add category field

my_array = []

my_array[:posts] = Posts.all.to_a.map { |p| p.data }

How can I merge them to see this result?

my_array: {[ category1, title1, description1, slug1], [ category2, title2, description2, slug2]}

So, I want to push the category field into the same array, but I don't know how to change this query

 my_array[:posts] = Posts.all.to_a.map { |p| p.data }

Upvotes: 0

Views: 172

Answers (1)

Mshka
Mshka

Reputation: 1828

if you want to merge the category to the hash you will need to get the data then merge a category key with the category

my_array[:posts] = Posts.all.to_a.map { |p| p.data.merge(category: p.category) }

Upvotes: 1

Related Questions