使用 jbuilder 的哈希数组作为哈希键和值作为数组

array of hashes as hash key and value as array using jbuilder

我正在尝试使用 Jbuilder

生成 JSON 响应

我有一个这样的哈希数组

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

我想将其转换为 JSON。 这里的逻辑是将所有术语作为键并将其定义推入数组

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

到目前为止我取得的成就是

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

给我

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

有人能帮我解决这个问题吗?

您正在寻找这样的东西,

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

如果:term:definition的顺序不保证,需要在原始hash上中间调用.map(&:sort),应该读取:shift作为 :pop 因为排序后 :definitions 将在 :terms 之前。

最简单的解决方案:)

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