Filtering a nested json for a particular flied and returning adjacent member in ruby

Viewed 62

I have an API response of the following structure

{
  "id": "123342-123412",
  "data": [
    {
      "id": "ace123",
      "name": "Tom",
      "files": [
        {
          "color": "yellow",
          "file_id": "245"
        },
        {
          "color": "red",
          "file_id": "233"
        }
      ]
    },
    {
      "id": "asd123",
      "name": "Jerry",
      "files": [
        {
          "color": "red",
          "file_id": "210"
        },
        {
          "color": "green",
          "file_id": "221"
        }
      ]
    },
    {
      "id": "acs123",
      "name": "Barbie",
      "files": [
        {
          "color": "green",
          "file_id": "201"
        }
      ]
    }
  ]
}

I am new to ruby, I want to filter out all file ids with the color red, what's the better way of doing it rather than iterating through the whole JSON using

data.each do  | object| 
# individual element search code 
end

I am using ruby version 2.6

1 Answers

The single line version that comes to my mind is:

json[:data].map {|d| d[:files] }.flatten.select {|f| f[:color] == 'red' }.map {|f| f[:file_id] }
=> ["233", "210"]

But this iterates multiple times (one for every method call), not to mention it looks kind of cryptic to me.
Personally I would prefer a verbose version, where it's clearly stated how's getting the values:

file_ids = []
json[:data].each do |data| 
  data[:files].each do |file| 
    next if file[:color] != 'red'

    file_ids << file[:file_id]
  end
end
file_ids.uniq # In case you have duplicates

But is up to you what to use.

Related