简体   繁体   中英

Merge hash with array of hashes based on value in shared key

I start with the following:

@prod = []
@num = []
@todd = [{:sellersku=>"2273500028", :num=>"B0076E32F8", :price=>"15.49"}, 
{:sellersku=>"5154464774", :num=>"B00013J6HY", :price=>"445.94"}]

Then create a lookup array:

@todd.each do |x|  
  @num << x[:num]
end

Then using the lookup array go thru an API that loads various data into results:

@num.each do |x|
call_api(x) #I left out the code that populates the variables below..
results = {:num => x,  
:vendor => vendor, :type => type, :color => @color, :image => hi_image
}
end

When the above finishes calling the api, I want to merge the @todd array and the results array into the @prod array of hashes. Resulting in this.

[{:sellersku=>"2273500028", :num=>"B0076E32F8", :price=>"15.49",
:vendor => "Boss", :type => "Shoes", :color => "Blue", :image => boss.jpg}, 
{:sellersku=>"5154464774", :num=>"B00013J6HY", :price=>"34.49",
:vendor => "Converse", :type => "Shirt", :color => "Orange", 
:image => cons.jpg}]
@prod = []
@num = []
@todd = [
  {:sellersku=>"2273500028", :num=>"B0076E32F8", :price=>"15.49"},
  {:sellersku=>"5154464774", :num=>"B00013J6HY", :price=>"445.94"}
]

@todd.each do |hash|
  serial_number = hash[:num]

  # EXTERNAL CALL TO API
  info = api_call(serial_number) #likely returns json
  # parse into new hash called results

  results = {
    :vendor => vendor,
    :type => type,
    :color => @color,
    :image => hi_image
  }

  @prod << hash.merge(results)
end

@prod
# after iteration, @prod will have all the information you are looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM