如何基于Rails中的哈希键合并哈希数组 [英] How to merge arrays of hashes based on keys of hashes in Rails
本文介绍了如何基于Rails中的哈希键合并哈希数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想根据唯一性合并这两个数组:
I want to merge these two arrays based on uniqueness:
"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
来替换发现匹配的散列。
So if I start with the user_variables
array and add template_variables
to it, replacing hashes where matches are found.
我想要的输出是:
My desired output would be:
"new_variables": [{
"info_top": "Some string"
}, {
"info_bottom": "Other string"
}, {
"other_info": "Default number"
}]
我试过 user_variables.merge template_variables)
及其变体,但它不适用于哈希数组。
I've tried user_variables.merge(template_variables)
and variations on that, but that's not suitable for an array of hashes, it seems.
如何做到这一点?
推荐答案
(first_array + second_array).uniq{|hash| hash.keys.first}
但是您的数据结构很糟糕。
but your data structure sucks.
这篇关于如何基于Rails中的哈希键合并哈希数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文