2015-10-08 117 views
0

我怎样才能变换散列数组:如何通过一个键和合并内键和阵列散列组阵列

[{ 
    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函数获得这个[原文如此]的结果是否最好?

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

回答

1

您不能使用变量名称in,因为它是关键字。我将使用iin来代替。

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

您可能想使用'flat_map',因为海报希望生成的数组变平。 :-) – Drenmi

+0

@Drenmi谢谢。你是对的。 – sawa