Ruby Rails如何从数组中的数组中的数组中获取值?

时间:2018-12-13 17:24:46

标签: ruby-on-rails arrays json ruby

我想从JSON数组中获取值,可以将其分配给表列,但是我需要的值之一是在数组中的数组中,在数组中。例如,一组员工,每个员工都有一个部门,每个部门包含多个楼层。

{"employees": [{"name": "bob", "age": 20, "department": ["location": "head office", "floors":["ground", "basement"]], "grade": "supervisor"}]}

姓名和年龄按预期显示,但我不确定如何发言。我尝试了几种方法,但无法获得“地板”。这是我的最新尝试,但是它表示@employee [:department]行上的字符串到整数的无效转换。有人可以建议获得此价值的最佳方法吗?谢谢

@employees.each do |i|
 employee[:column1] = i[:name]
 employee[:column2] = i[:age]

 @employee[:department].each do |d|
  employee[:column3] = d[:floors]
 end
end

2 个答案:

答案 0 :(得分:1)

问题在于,当我认为您想遍历@employee[:department]时,您正在遍历i[:department]

你可以做

 @employees.values.flatten.each do |i|
     employee[:column1] = i[:name]
     employee[:column2] = i[:age]

     i[:department].each do |d|
         employee[:column3] = d[:floors]
     end
 end 

答案 1 :(得分:0)

您可以尝试一下:

colnames(df) <- c("Fac", "m.Jan", "m.Feb", "m.Mar", "m.Apr", "m.May", "m.Jun",
                    "m.Jul", "m.Aug","m.Sep", "m.Oct", "m.Nov", "m.Dec")

由于@employees.each do |e| employee[:column1] = e[:name] employee[:column2] = e[:age] employee[:column3] = e[:department].last[:floors] end 总是以数组的最后一个元素结尾,因此无需进行迭代。因此,您可以继续使用employee[:column3] = d[:floors]

为您节省了几行内容和一些键入操作。