I'm getting data from an API and need to format it differently. I have a car_array that consists of an array of hashes. However, sometimes there will be a sub-array as one of the hash values that contains more than 1 element. In this case, there should be a loop so that each element in the array gets mapped correctly as separate entries.
An example of data, note how prices and options_package are arrays with multiple elements.
[{ dealer_id: 1, dealer_name: "dealership 1", car_make: "jeep", prices: ['30', '32', '35'], options_package: ['A', 'B', 'C'] }, { dealer_id: 2, dealer_name: "dealership 2", car_make: "ford", prices: ['50', '55'], options_package: ['X', 'Y'] }, { dealer_id: 3, dealer_name: "dealership 3", car_make: "dodge", prices: ['70'], options_package: ['A'] }] I would like to create multiple entries when there are multiple array elements
for example, the data above should be broken out and mapped as:
some_array = [ { dealer_id: 1, dealer_name: "dealership 1", car_make: "jeep", price: '30', options_package: 'A' }, { dealer_id: 1, dealer_name: "dealership 1", car_make: "jeep", price: '32', options_package: 'B' }, { dealer_id: 1, dealer_name: "dealership 1", car_make: "jeep", price: '35', options_package: 'C' }, { dealer_id: 2, dealer_name: "dealership 2", car_make: "ford", price: '50', options_package: 'X' }, { dealer_id: 2, dealer_name: "dealership 2", car_make: "ford", price: '55', options_package: 'Y' }, { dealer_id: 3, dealer_name: "dealership 3", car_make: "dodge", price: '70', options_package: 'A' } ] Here's what I've got so far:
car_arr.each do |car| if car['Prices'].length > 1 # if there are multiple prices/options loop through each one and create a new car car.each do |key, value| if key == 'Prices' value.each do |price| formatted_car_array << { dealer_id: car['dealer_id'], dealer_name: car['dealer_name'], car_make: car['make'], options_package: ???????, price: price, } end end end else # there's only element for price and options_package formatted_car_array << { dealer_id: car['dealer_id'], dealer_name: car['dealer_name'], car_make: car['make'], options_package: car['options_package'], price: car['prices'] } end end