2017-09-14 33 views
1

我试图用Jbuilder的阵列使用JBuilder的

我有散列这样

words= [ 
     {"term": "abc", 
     "definition": "123" 
     } , 
     {"term": "abc", 
     "definition": "345" 
     } , 
     {"term": "xyz", 
     "definition": "890" 
     } 
    ] 

阵列生成JSON响应哈希哈希键和值作为数组的,我想这个秘密进入JSON。这里 逻辑是采取所有条款键和推动它定义成阵列

{ 
    "abc": ["123","345"], 
    “xyz”: ["890"] 
    } 

我取得了什么至今

words.each do |word| 
    json.set! word['text'] ,word['definition'] 
end 

给我

{ 
    "abc": "123" 
    "abc": "345", 
    "xyz": "890" 
} 

可能有的帮我在这。

回答

0

简单的解决方案:)

words= [ 
     {"term": "abc", 
     "definition": "123" 
     } , 
     {"term": "abc", 
     "definition": "345" 
     } , 
     {"term": "xyz", 
     "definition": "890" 
     } 
    ] 

result_hash = Hash.new{|hsh, key| hsh[key]=[] } 
words.map{|x| result_hash[x[:term]].push(x[:definition])} 

你的输出将在result_hash

+0

它可能更短:'words.each_with_object({}){| x,acc | (acc [x [:term]] || = [])<< x [:definition]}',但OP要求提供jbuilder解决方案。 – mudasobwa

0

您正在寻找这样的事情,

words = [{:term=>"abc", :definition=>"123"}, {:term=>"abc", :definition=>"345"}, {:term=>"xyz", :definition=>"890"}] 
words.inject({}) do |h, w| 
    h[w[:term]] ||= [] 
    h[w[:term]] << w[:definition] 
    h 
end 
#=> {"abc"=>["123", "345"], "xyz"=>["890"]} 
+0

我们可以用JBuilder的同样的事情? –

0
words.group_by{|d| d[:term]}.map{|k,v| {k => v.map{|val| val[:definition]}}}.reduce(&:merge) 
0
words.map(&:values).group_by(&:shift).each do |k, values| 
    json.set! k, values.flatten 
end 

如果:term:definition顺序不能保证,有需要.map(&:sort)中间调用原始哈希,和:shift应该被认为是:pop,因为排序后:definition s会在:term s之前。