简体   繁体   中英

How to merge arrays of hashes based on keys of hashes in 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"
}]

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"
}]

I've tried user_variables.merge(template_variables) and variations on that, but that's not suitable for an array of hashes, it seems.

How do I do this?

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

但是您的数据结构糟透了。

If:

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"}]
       }

Then try this:

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

returns:

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

You can simply do something like

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

Which is similar to Mladen Jablanović post

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM