[英]Merge hash with array of hashes based on value in shared key
我從以下內容開始:
@prod = []
@num = []
@todd = [{:sellersku=>"2273500028", :num=>"B0076E32F8", :price=>"15.49"},
{:sellersku=>"5154464774", :num=>"B00013J6HY", :price=>"445.94"}]
然后創建一個查找數組:
@todd.each do |x|
@num << x[:num]
end
然后使用查找數組通過一個將各種數據加載到結果中的API:
@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
當上面的API調用完成后,我想將@todd數組和results數組合並到哈希的@prod數組中。 結果就是這樣。
[{: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.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.