1

I'm quite new to Rails and I've been attempting to flatten out an array of JSON objects fetched from the DB in my controller to assemble a flattened data structure to pass into my cross filter (i'm making some dc.js visualizations). I've managed to get an nested array of objects like so:

['class': 'biology', 'category': 'science', 'students': [{'name': 'sarah', 'year':freshman}, {'name':'bob', 'year': 'sophomore'}] ]

This is the structure that I'm aiming to achieve:

[ {'name':'sarah', 'year':'freshman', 'class': 'biology', 'category': 'science'}, {'name':'bob', 'year': 'sophomore', 'class': 'biology', 'category': 'science'}]

I've managed to build an array of these JSON objects in my controller with the class to students association through my controller, but I've totally hit a wall on how to properly flatten out the dataset as an array of UN-nested objects. I'd essentially like to flatten out an object for each student and have that as one object represented in the new array. Any pointers would be much appreciated.

So far, I've come across utilizing:

JSON.parse(objects).each do |obj|
   #flatten json here
end

Is it just a matter of iterating through the students attribute, and for each student create a new object with all the associated attributes? Any pointers in the right direction would be much appreciated.

1 Answer 1

1

Yeah, you would do something like this:

students_with_classes = JSON.parse(objects).map do |obj|
   obj['students'].map { |student| student.merge(obj.except('students')) }
end.flatten
Sign up to request clarification or add additional context in comments.

3 Comments

thanks for the input! It seems to be working, but what I end up getting is a nested array now.. [ [{'name':'sarah', 'year':'freshman', 'class': 'biology', 'category': 'science'}] , [{'name':'bob', 'year': 'sophomore', 'class': 'biology', 'category': 'science'}] ]. Do I just flatten the array?
Thanks for the input. On another note, I noticed that JSON.parse.map changes the object type when you parse the JSON object. I've checked the type, and it's passed in as a JSON string that is called on an ActiveRecord Relation, but the end result after mapping and parsing is an array.. and when i try to access the individual objects of the end result array, it's accessed as individual characters vs pulling out an object. How can I convert it back to a json string in order to access individual objects vs. single characters?
How are you accessing the final array? Please don't forget to upvote answers if they are useful to you :)

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.