![](/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.