如何通过一个键对哈希数组进行分组,并合并内部键和数组

时间:2015-10-08 08:46:51

标签: arrays ruby hash

如何转换哈希数组:

[{
  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"}]
}

在一个区块更聪明,然后在[sic]示例中?用ruby函数获得这个[原文如此]的结果是否最好?

in = _
out = {properties: []}
in.map {|i| out[:id] = i[:ref_id]; out[:properties] << i[:properties]; out[:type] = i[:type]}
out[:properties].flatten!

1 个答案:

答案 0 :(得分:1)

您不能使用变量名in,因为它是关键字。我会改用iin

out = {
  id: iin.last[:ref_id],
  type: iin.last[:type],
  properties: iin.flat_map{|e| e[:properties]}
}