ruby on rails - array of hashes as hash key and value as array using jbuilder -
i'm trying generate json response using jbuilder
i have array of hashes this
words= [ {"term": "abc", "definition": "123" } , {"term": "abc", "definition": "345" } , {"term": "xyz", "definition": "890" } ]
i covert json. logic here take terms keys , push it's definitions arrays
{ "abc": ["123","345"], “xyz”: ["890"] }
what achieved far
words.each |word| json.set! word['text'] ,word['definition'] end
gives me
{ "abc": "123" "abc": "345", "xyz": "890" }
could me on this.
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 in result_hash
Comments
Post a Comment