Search code examples
ruby-on-railsrubyjbuilder

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


I'm trying to generate JSON response using Jbuilder

I have an array of hashes like this

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

I would like covert this into JSON. logic here is take all terms as keys and push it's definitions into arrays

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

What I achieved so far is

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

gives me

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

Could some help me on this.


Solution

  • simplest solution :)

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

    your output will be in result_hash