I am trying to use the jQuery plugin jQCloud to create word clouds in a rails application.
The word cloud data needs to be in a format:
var word_array = [
{text: "Lorem", weight: 15},
{text: "Ipsum", weight: 9},
];
I currently have a ruby hash of word frequencies like:
{"people"=>111, "other"=>110}
How can I convert this into the required named javascript array, like:
[{text: "people", weight: 11},{text: "other", weight: 11}]
Any ideas or suggestions would be greatly appreciated!
Thanks
Just use map
:
hash.map { |k, v| { text: k, weight: v } }
=> [{:text=>"people", :weight=>111}, {:text=>"other", :weight=>110}]
hash = {"people"=>111, "other"=>110}
p hash.map { |a| Hash[[:text, :weight].zip(a)] }
# => [{:text=>"people", :weight=>111}, {:text=>"other", :weight=>110}]
You could try this
hash = {"people"=>111, "other"=>110}
hash.to_a.map {|k,v| [{"text" => k},{"wieght" => v}]}.flatten
=> [{"text"=>"people"}, {"wieght"=>111}, {"text"=>"other"}, {"wieght"=>110}]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.