4

i have a hash with array object :

{
  false=>[#<Campaign id: 1, name: "campaign 1", active: false>, #<Campaign id: 3, name: "campaign 3", active: false>, #<Campaign id: 4, name: "campaign 4", active: false>], 
  true=>[#<Campaign id: 2, name: "campaign 2", active: true>]
} 

how to convert above hash to hash

{
  false=>[{id:1, name:"campaign 1"}, {id:3, name: "capaign 3"}, ....],
  true =>[{id:2, name:"campaign 2"}]
}

2 Answers 2

3
hash.each {|k,v| hash[k] = v.map{|e| {id: e[:id], name: e[:name]}}}

and if you can use select_all method get the array of hash, not array of object, so you doesn't need to covert object to hash.

ModelName.connection.select_all("select id, name from <table_name>;")
=> [{id:xxx, name: xxx}.......]
Sign up to request clarification or add additional context in comments.

Comments

0

Use attributes method on your object

attributes() public

Returns a hash of all the attributes with their names as keys and the values of the attributes as values.

hash = {
  false => [#<Campaign id: 1, name: "campaign 1", active: false>, #<Campaign id: 3, name: "campaign 3", active: false>, #<Campaign id: 4, name: "campaign 4", active: false>], 
  true  => [#<Campaign id: 2, name: "campaign 2", active: true>]
} 

So this line should do the trick -

hash.each {|k, v| hash[k] = v.map(&:attributes) }

{
  false => [{"id": 1, "name": "campaign 1", "active": false}, {"id": 3, "name": "campaign 3", "active": false}, {"id": 4, "name": "campaign 4", "active": false}], 
  true  => [{"id": 2, "name": "campaign 2", "active": true}]
}

1 Comment

Please edit with more information. Code-only and "try this" answers are discouraged, because they contain no searchable content, and don't explain why someone should "try this".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.