1

I want to get values from a JSON array which I can assign to a table column, however one of the values I need is in an array within an array, within an array. For example, an array of employees and for each employee there is an array of departments which contains an array of floors.

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

The name and age display as expected but I am unsure how to get the floors. I have tried several ways but I am unable to get the "floors". This is my latest attempt but it says invalid conversion of string to integer on the @employee[:department] line. Can someone advise the best way to get this value? Thanks

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

 @employee[:department].each do |d|
  employee[:column3] = d[:floors]
 end
end
1
  • 1
    Shouldn't it be i.[:department].each do |d|? Commented Dec 13, 2018 at 17:36

2 Answers 2

1

The problem is that you're iterating over @employee[:department] when I think you want to be iterating over i[:department].

You could do

 @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 
Sign up to request clarification or add additional context in comments.

Comments

0

You could give this a try:

@employees.each do |e|
  employee[:column1] = e[:name]
  employee[:column2] = e[:age]
  employee[:column3] = e[:department].last[:floors]
end

There's no need to iterate since the employee[:column3] = d[:floors] will always end up with the last element of the array. So, you can just go ahead and use last.

Saves you a couple of lines and some typing.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.