我有一個回傳這個陣列和散列的查詢。如何更改散列并向其添加新的鍵值對, import_id: 1, cost: 0或者我可以map對查詢進行操作嗎?
查詢
name = Store.joins(:paid => :supply).group(:name).select("supply.name").where("stores.identifier IN (?) ", tids).pluck(:supply_id, :name)
大批
[[258, "Square"], [245, "App"]]
當我將它轉換為哈希時它回傳
{258=>"Square", 245=>"App"}
期望的輸出
{{supply_id: 258, name: "Square", import_id: 1, cost: 0}, {supply_id: 245, name: "App", import_id: 1, cost: 0}}
uj5u.com熱心網友回復:
看來回應是一[supply_id, name]對陣列。您可以輕松地解構陣列并將資料重組為具有適當符號鍵的散列。
array = [[258, "Square"], [245, "App"]]
array.map do |(id, name)|
{ supply_id: id, name: name, import_id: 1, cost: 0 }
end
# [{:supply_id=>258, :name=>"Square", :import_id=>1, :cost=>0}, ...]
uj5u.com熱心網友回復:
使用#select代替#pluck和呼叫.as_json或.map(&:attributes)
Store.joins(:paid => :supply).group(:name)
.select("supply.name").where("stores.identifier IN (?) ", tids)
.select(:supply_id, :name).as_json
# [{supply_id: 258, name: "Square"}, {supply_id: 245, name: "App"}]
或者
Store.joins(:paid => :supply).group(:name)
.select("supply.name").where("stores.identifier IN (?) ", tids)
.select(:supply_id, :name).map(&:attributes)
# [{supply_id: 258, name: "Square"}, {supply_id: 245, name: "App"}]
或者你可以構造帶有{import_id: 1, cost: 0}附加的哈希
Store.joins(:paid => :supply).group(:name)
.select("supply.name").where("stores.identifier IN (?) ", tids)
.select(:supply_id, :name)
.map {|e| {supply_id: e.supply_id, name: e.name, import_id: 1, cost: 0} }
# [{supply_id: 258, name: "Square", import_id: 1, cost: 0}, {supply_id: 245, name: "App", import_id: 1, cost: 0}]
或者
您可以Hash#merge在哈希生成步驟期間使用以包括{import_id: 1, cost: 0}
hash.merge({import_id: 1, cost: 0})
# To achieve: {{supply_id: 258, name: "Square", import_id: 1, cost: 0}, {supply_id: 245, name: "App", import_id: 1, cost: 0}}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/331871.html
