Convert object with array values into array of object

Advertisements

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.

[
 { 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] ||= {}

Leave a ReplyCancel reply