![](/img/trans.png)
[英]Merge arrays of hashes into one array, and then group all the hashes based on matching id's
[英]How to group array of hashes by one key and merge inner keys and arrays
如何轉換哈希數組:
[{
id: 115,
ref_id: 440000000000337,
properties: [{name: "test"}],
type: "content"
},{
id: 116,
ref_id: 440000000000337,
properties: [{name: "asdf"}],
type: "content"
}]
得到期望的結果:
{
id: 440000000000337
type: "content"
properties: [{name: "test"}, {name: "asdf"}]
}
在示例中比[原文如此]聰明得多? 用ruby函數獲得此[sic]結果是否最好?
in = _
out = {properties: []}
in.map {|i| out[:id] = i[:ref_id]; out[:properties] << i[:properties]; out[:type] = i[:type]}
out[:properties].flatten!
您不能在其中使用變量名稱in
因為它是關鍵字。 我將使用iin
代替。
out = {
id: iin.last[:ref_id],
type: iin.last[:type],
properties: iin.flat_map{|e| e[:properties]}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.