我想基于唯一性合并这两个数组:
"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"
}]
因此,如果我从user_variables
数组开始并向其添加template_variables
,请替换找到匹配项的哈希值。
我想要的输出是:
"new_variables": [{
"info_top": "Some string"
}, {
"info_bottom": "Other string"
}, {
"other_info": "Default number"
}]
我已尝试user_variables.merge(template_variables)
及其变体,但似乎并不适合散列数组。
我该怎么做?
答案 0 :(得分:3)
(first_array + second_array).uniq{|hash| hash.keys.first}
但您的数据结构很糟糕。
答案 1 :(得分: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"}]
}
答案 2 :(得分:0)
您可以简单地执行类似
的操作 kk = {"aa": [{a: 1}, {b: 2}]}
jk = {"bb": [{a:3}, {d: 4}]}
(kk.values+jk.values).flatten.uniq{|hash| hash.keys.first}
类似于MladenJablanović的帖子