我有這樣的陣列
data =
[
{ :lineItemKey=>57, :sku=>"12GA-RIO",
:name=>"12 Gauge", :quantity=>4, :unitPrice=>5.76 },
{ :lineItemKey=>168, :sku=>"22LR-CAS-40-CPRN-50",
:name=>"22 Long", :quantity=>2, :unitPrice=>7.6 },
{ :lineItemKey=>57, :sku=>"12GA-RIO",
:name=>"12 Gauge", :quantity=>1, :unitPrice=>5.76 },
{ :lineItemKey=>236, :sku=>"300BLK-UNWD-CTC-220-BTHP-20",
:name=>"300 BLK", :quantity=>1, :unitPrice=>31.2 }
]
如果 sku 相同,我需要對數量求和并洗掉重復項。所以輸出應該是這樣的:
data =
[
{ :lineItemKey=>57, :sku=>"12GA-RIO",
:name=>"12 Gauge", :quantity=>5, :unitPrice=>5.76 },
{ :lineItemKey=>168, :sku=>"22LR-CAS-40-CPRN-50",
:name=>"22 Long", :quantity=>2, :unitPrice=>7.6 },
{ :lineItemKey=>236, :sku=>"300BLK-UNWD-CTC-220-BTHP-20",
:name=>"300 BLK", :quantity=>1, :unitPrice=>31.2 }
]
uj5u.com熱心網友回復:
data.each_with_object({}) do |g,h|
h.update(g[:lineItemKey]=>g) do |_k, old_hash, new_hash|
old_hash.merge(quantity: old_hash[:quantity] new_hash[:quantity])
end
end.values
#=> [
# {:lineItemKey=>57, :sku=>"12GA-RIO", :name=>"12 Gauge",
# :quantity=>5, :unitPrice=>5.76},
# {:lineItemKey=>168, :sku=>"22LR-CAS-40-CPRN-50", :name=>"22 Long",
# :quantity=>2, :unitPrice=>7.6},
# {:lineItemKey=>236, :sku=>"300BLK-UNWD-CTC-220-BTHP-20",
# :name=>"300 BLK", :quantity=>1, :unitPrice=>31.2}
# ]
請注意,接收方values是
{
57=>{:lineItemKey=>57, :sku=>"12GA-RIO", :name=>"12 Gauge",
:quantity=>5, :unitPrice=>5.76},
168=>{:lineItemKey=>168, :sku=>"22LR-CAS-40-CPRN-50",
:name=>"22 Long", :quantity=>2, :unitPrice=>7.6},
236=>{:lineItemKey=>236, :sku=>"300BLK-UNWD-CTC-220-BTHP-20",
:name=>"300 BLK", :quantity=>1, :unitPrice=>31.2}
}
這使用了Hash#update (aka merge!) 的形式,它使用一個塊來計算存在于被合并的兩個散列中的鍵的值。這里那個塊是
do |_k, old_hash, new_hash|
old_hash.merge(quantity: old_hash[:quantity] new_hash[:quantity])
end
有關三個塊變數的定義,請參見檔案。前面的下劃線k(通用鍵)旨在向讀者表明它不用于塊計算(通常只是下劃線的通用約定)。
uj5u.com熱心網友回復:
輸入
data =
[
{ :lineItemKey=>57, :sku=>"12GA-RIO",
:name=>"12 Gauge", :quantity=>4, :unitPrice=>5.76 },
{ :lineItemKey=>168, :sku=>"22LR-CAS-40-CPRN-50",
:name=>"22 Long", :quantity=>2, :unitPrice=>7.6 },
{ :lineItemKey=>57, :sku=>"12GA-RIO",
:name=>"12 Gauge", :quantity=>1, :unitPrice=>5.76 },
{ :lineItemKey=>236, :sku=>"300BLK-UNWD-CTC-220-BTHP-20",
:name=>"300 BLK", :quantity=>1, :unitPrice=>31.2 }
]
代碼
p data.group_by { |x| x[:lineItemKey] }
.values
.map { |arr| arr.reduce { |h1, h2| h1.merge(h2) { |k, oldv, newv| k.eql?(:quantity) ? oldv = newv : oldv } } }
輸出
[
{ :lineItemKey=>57, :sku=>"12GA-RIO",
:name=>"12 Gauge", :quantity=>5, :unitPrice=>5.76 },
{ :lineItemKey=>168, :sku=>"22LR-CAS-40-CPRN-50",
:name=>"22 Long", :quantity=>2, :unitPrice=>7.6 },
{ :lineItemKey=>236, :sku=>"300BLK-UNWD-CTC-220-BTHP-20",
:name=>"300 BLK", :quantity=>1, :unitPrice=>31.2 }
]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/410168.html
標籤:
上一篇:從哈希Ruby列印指定值
下一篇:Ruby進入遞回
