[英]How to group array of hashes by one key and merge inner keys and arrays
How can I transform an array of hashes: 如何转换哈希数组:
[{
id: 115,
ref_id: 440000000000337,
properties: [{name: "test"}],
type: "content"
},{
id: 116,
ref_id: 440000000000337,
properties: [{name: "asdf"}],
type: "content"
}]
to get the desired result: 得到期望的结果:
{
id: 440000000000337
type: "content"
properties: [{name: "test"}, {name: "asdf"}]
}
in one block smarter then [sic] in the example? 在示例中比[原文如此]聪明得多? Would it be best to obtain this [sic] results with ruby functions?
用ruby函数获得此[sic]结果是否最好?
in = _
out = {properties: []}
in.map {|i| out[:id] = i[:ref_id]; out[:properties] << i[:properties]; out[:type] = i[:type]}
out[:properties].flatten!
You cannot use the variable name in
since it is a keyword. 您不能在其中使用变量名称
in
因为它是关键字。 I will use iin
instead. 我将使用
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.