鉴于数据:
data = [ {"id":14,"sort":1,"content":"9",foo: "2022"},{"id":14,"sort":4,"content":"5","sort":2,"content":"1","sort":3,"content":"0",{"id":15,"content":"4",foo: "2888"},"content":"3",{"id":16,"content":"8",foo: "3112"},foo: "3112"} ]
得到的内容由他们的排序和ID连接:
formatted = data.group_by { |d| d[:id]}.transform_values do |value_array| value_array.sort_by { |b| b[:sort] } .map { |c| c[:content] }.join end puts formatted #=> {14=>"9105",15=>"3134",16=>"8449"}
我知道foo存在于value_array中,但想知道如何在格式化变量中包含foo,以便我可以通过它来映射以获得所需的输出,或者是否可能?
期望的输出:
[ {"id":14,"concated_value":"9105","concated_value":"3134","concated_value":"8449",foo: "3112"} ]
解决方法
因为:foo是唯一的:id.你可以这样做:
data.group_by {|h| h[:id]}.map do |_,sa| sa.map(&:dup).sort_by {|h| h.delete(:sort) }.reduce do |m,h| m.merge(h) {|key,old,new| key == :content ? old + new : old } end.tap {|h| h[:concated_value] = h.delete(:content) } end #=> [ # {"id":14,foo: "2022","concated_value":"9105"},# {"id":15,foo: "2888","concated_value":"3134"},# {"id":16,foo: "3112","concated_value":"8449"} # ]
>首先我们按ID分组. group_by {| h | H [:ID]}>然后我们复制组中的哈希值(以免破坏原始组合).地图(安培;:DUP)>然后我们按排序排序并同时删除它. .sort_by {| h | h.delete(:sort)}>然后我们将组合并在一起并仅连接内容密钥.m.merge(h){| key,new | key ==:内容?老新:老}>然后我们只需将内容的密钥更改为concated_value tap {| h | h [:concated_value] = h.delete(:content)}