Home > Software design >  How to convert an object to an array?
How to convert an object to an array?

Time:05-29

I am creating a Rails 5.2 app. In this app I let my users save their settings to a JSONB attribute.

The data is posted from an Android app and looks like this:

{"email"=>true, "alert"=>true, "push"=>true}

I need to save this data as an array into the database. This is my desired outcome.

[{"email"=>true}, {"alert"=>true}, {"push"=>true}]

I tried this:

object = {"email"=>true, "alert"=>true, "push"=>true}
object.to_a

But it rendered:

[["email", true], ["alert", true], ["push", true]]

CodePudding user response:

Try this using the to_a you have tried

object = {"email"=>true, "alert"=>true, "push"=>true}
result = object.to_a.map{ |b| [b].to_h }

Or

object = {"email"=>true, "alert"=>true, "push"=>true}
result = object.map{ |key, val| [[key, val]].to_h }

CodePudding user response:

arr=h.map{|k,v| [k,v].to_h}
p arr
  • Related