2015-10-08 120 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