javascript - 如何在不创建多维数组的情况下在 ROR 中创建 json 对象

标签 javascript ruby-on-rails ruby json

例如,如果我尝试创建这样的东西

@json = Array.new

for x in 0..1
    y = 2
    @json << ["Id" => x, "Label" => y]
 end
respond_to do |format|
  format.html # index.html.erb
  format.json { render :json => @nodes }
end

这是返回的 JSON:

[[{"Id":0,"Label":2}], [{"Id":1,"Label":2}]]

然后如果我想在 java 脚本中访问它,我必须执行 array[i][0].id 来找到 id。当我应该能够执行 array[i].id 来获取 id 时。

有什么建议吗?

最佳答案

您使用 [] 构建哈希,您必须使用 {}。并且不要初始化 + 循环 + 推送,这不是惯用的 Ruby。我会写:

@json = (0..1).map { |id| {"Id" => id, "Label" => 2} }
#=> [{"Id"=>0, "Label"=>2}, {"Id"=>1, "Label"=>2}]

关于javascript - 如何在不创建多维数组的情况下在 ROR 中创建 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10724657/

相关文章:

ruby - 在 OS X 上部署 Ruby-Tk 应用程序

ruby-on-rails - 如何在一个页面上使用多个 map ?

javascript - 按数据属性和父子关系对li进行排序

javascript_include_tag :application loads javascripts twice in development environment

mysql - 我怎样才能安装mysql2?

ruby - 如何在ruby中对文件进行排序

javascript - 在angularjs中的$scope成员函数内引用函数内的变量

javascript - document.body 返回 iframe 主体

javascript - sproutcore主页重构

ruby-on-rails - 为什么 Rails 在 schema.rb 中的所有列上设置 ":null => false"?