Filter JSON array by value with Ruby

require 'json'

arr = JSON.parse <<END_OF_JSON
[
 {"name":"Idaho","state":{"id":1,"name":"A"}},
 {"name":"Wyoming","state":{"id":1,"name":"A"}},
 {"name":"Montana","state":{"id":2,"name":"B"}},
 {"name":"South Dakota","state":{"id":1,"name":"B"}}
]
END_OF_JSON

results = []

arr.each do |hash|
  results << hash["name"] if hash["state"]["name"] == "A"
end

p results

--output:--
["Idaho", "Wyoming"]

require 'json'

json = <<'JSON_STRING'
[
 {"name":"Idaho","state":{"id":1,"name":"A"}},
 {"name":"Wyoming","state":{"id":1,"name":"A"}},
 {"name":"Montana","state":{"id":2,"name":"B"}},
 {"name":"South Dakota","state":{"id":1,"name":"B"}}
]
JSON_STRING

data = JSON.parse json

data.map(&:values).select { |state, values| values["name"] == ?A }
#=> [["Idaho", {"id"=>1, "name"=>"A"}], ["Wyoming", {"id"=>1, "name"=>"A"}]]

data.map(&:values).select { |state, values| values["name"] == ?A }.map(&:first)
#=> ["Idaho", "Wyoming"]

Tags:

Arrays

Ruby

Json