如何为jquery自动完成映射我的哈希数组?

时间:2012-02-24 19:10:05

标签: ruby json jquery-autocomplete

我有这个红宝石对象

options = [
  {"ActionScript"=>"orange"},
  {"AppleScript"=>"orange"},
  {"Asp"=>"red"},
  {"BASIC"=>"green"},
  {"C"=>"blue"},
  {"C++"=>"purple"},
  {"Clojure"=>"green"},
  {"COBOL"=>"red"},
  {"ColdFusion"=>"red"},
  {"Erlang"=>"green"},
  {"Fortran"=>"orange"},
  {"Groovy"=>"green"},
  {"Haskell"=>"green"},
  {"Java"=>"green"},
  {"JavaScript"=>"brown"},
  {"Lisp"=>"purple"},
  {"Perl"=>"blue"},
  {"PHP"=>"red"},
  {"Python"=>"green"},
  {"Ruby"=>"green"},
  {"Scala"=>"green"},
  {"Scheme"=>"orange"}
]

并且我希望将其映射到此:

[{"name":"ActionScript","value":"orange"},{"name":"AppleScript","value":"orange"}...]

提前致谢。

3 个答案:

答案 0 :(得分:2)

require 'json'

options.map {|elem| elem.map {|k,v| {:name => k, :value => v}}}.flatten.to_json

答案 1 :(得分:2)

options.map do |option| 
  key, value = option.first
  {"name" => key, "value" => value} 
end # add .to_json if you want a JSON string

此外:

options.reduce(:merge).map { |k, v| {"name" => k, "value" => v} }

答案 2 :(得分:1)

您可以简单地使用to_json方法

 require 'json' 
 options = options.map {|elem| elem.map {|k,v| {:name => k, :value => v}}}.flatten 
 js_options = options.to_json