2016-07-14 37 views
0

我想基於獨特性這兩個數組合並:如果我開始與user_variables陣列如何合併基於哈希鍵散列的陣列中的Rails

"template_variables": [{ 
    "info_top": "Some string" 
}, { 
    "info_bottom": "Other string" 
}], 


"user_variables": [{ 
    "info_top": "Default string" 
}, { 
    "info_bottom": "Other default string" 
}, { 
    "other_info": "Default number" 
}] 

所以並添加template_variables它,更換哈希找到匹配的地方。

我所需的輸出是:

"new_variables": [{ 
    "info_top": "Some string" 
}, { 
    "info_bottom": "Other string" 
}, { 
    "other_info": "Default number" 
}] 

我試着對user_variables.merge(template_variables)和變化,但是這並不適合哈希的數組,它似乎。

我該怎麼做?

+0

什麼是理想的輸出到你上面的例子? – RSB

+0

「template_variables」數組和「user_variables」數組內的值是否總是以單個鍵作爲散列值?或者你能得到這樣的東西:''template_variables「:[{var1:'some str',var2:'str in var1'},{var3:'3rd str in'hash'}]' – br3nt

+1

Like @RSB表示,請添加所需的輸出。另外,請向我們提供您的解決方案(或者至少您的練習)的外觀。 –

回答

2
(first_array + second_array).uniq{|hash| hash.keys.first} 

但你的數據結構很爛。

+0

介意解釋爲什麼?另外,你的回答對我來說不起作用。 –

+1

_n_單個元素散列的數組,全部使用不同的鍵,而不是使用_n_元素的單個散列。另外,什麼不起作用?你會得到什麼結果? –

+0

這篇文章已經被大大簡化了,但是,我明白你的觀點,謝謝。雖然你的代碼只是返回兩個散列而沒有任何覆蓋。 –

1

如果:

hash = { "template_variables": 
     [{"info_top": "Some string"}, 
      {"info_bottom": "Other string"}], 

     "user_variables": 
     [{"info_top": "Default string"}, 
      {"info_bottom": "Other default string"}, 
      {"other_info": "Default number"}] 
     } 

那就試試這個:

values = hash.values.flatten.reverse.inject(&:merge!).map { |k,v| { k => v } } 
new_hash = {"new_variables": values} 

回報:

{ :new_variables => 
    [{:other_info => "Default number"}, 
    {:info_bottom => "Other string"}, 
    {:info_top => "Some string"}] 
} 
0

你可以簡單地這樣做

kk = {"aa": [{a: 1}, {b: 2}]} 
jk = {"bb": [{a:3}, {d: 4}]} 
(kk.values+jk.values).flatten.uniq{|hash| hash.keys.first} 

這類似於姆拉登Jablanović發佈