我正在構建一個 Rails 5.2 應用程式。在這個應用程式中,我正在使用統計資料。
我生成兩個物件:
{
"total_project": {
"website": 1,
"google": 1,
"instagram": 1
}
}
還有這個:
{
"total_leads": {
"website": 1,
"google": 2,
"client_referral": 1
}
}
我需要將這兩個物件合并為一個增加計數的物件。期望的結果是:
{
"total_both": {
"website": 2,
"google": 3,
"instagram": 1,
"client_referral": 1
}
}
我試過了,它在技術上有效,它合并了物件,但計數沒有更新:
@total_project = array_projects.group_by { |d| d[:entity_type] }.transform_values(&:count).symbolize_keys
@total_leads = array_leads.group_by { |d| d[:entity_type] }.transform_values(&:count).symbolize_keys
@total_sources = merged.merge **@total_project, **@total_leads
請注意,屬性(來源)是資料庫中的動態屬性,因此我無法對任何內容進行硬編碼。用戶可以添加自己的來源。
uj5u.com熱心網友回復:
@total_sources = @total_project.merge(@total_leads) do |key, ts_value, tp_value|
ts_value tp_value
end
如果可以有兩個以上的來源,請將所有內容放在一個陣列中并執行。
@total_sources = source_array.reduce do |accumulator, next_source|
accumulator.merge(next_source) { |key, v1, v2| v1 v2 }
end
uj5u.com熱心網友回復:
您可以按如下方式計算所需的結果。
arr = [{ "total_project": { "website": 1, "google": 1, "instagram": 1 } },
{ "total_leads": { "website": 1, "google": 2, "client_referral": 1 } }]
{ "total_both" => arr.flat_map(&:values)
.reduce { |h,g| h.merge(g) { |_,o,n| o n } } }
#=> {"total_both"=>{:website=>2, :google=>3, :instagram=>1, :client_referral=>1}}
注意
arr.flat_map(&:values)
#=> [{:website=>1, :google=>1, :instagram=>1},
# {:website=>1, :google=>2, :client_referral=>1}]
如果我使用Array#map這將是
arr.map(&:values)
#=> [[{:website=>1, :google=>1, :instagram=>1}],
# [{:website=>1, :google=>2, :client_referral=>1}]]
請參閱Enumerable#flat_map、Enumerable#reduce和Hash#merge的形式,該形式采用一個塊(此處{ |_,o,n| o n }),該塊回傳正在合并的兩個哈希中存在的鍵的值。merge有關三個塊變數(此處 和 )的定義,_請參見o檔案。n我已經命名了第一個塊變數(持有公共密鑰)_,以向讀者表明它沒有用于塊計算(常見的 Ruby 約定)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/473770.html
標籤:轨道上的红宝石
