Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert object with array values into array of object

I do have this kind of params

{"people" => 
  {
    "fname" => ['john', 'megan'],
    "lname" => ['doe', 'fox']
  }
}

Wherein i loop through using this code

result = []
params[:people].each do |key, values|
  
  values.each_with_index do |value, i|
    result[i] = {}
    result[i][key.to_sym] = value
  end

end

The problem on my code is that it always gets the last key and value.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
 { lname: 'doe' },
 { lname: 'fox' }
]

i want to convert it into

[
  {fname: 'john', lname: 'doe'},
  {fname: 'megan', lname: 'fox'}
]

so that i can loop through of them and save to database.

>Solution :

result[i] = {}

The problem is that you’re doing this each loop iteration, which resets the value and deletes any existing keys you already put there. Instead, only set the value to {} if it doesn’t already exist.

result[i] ||= {}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading