Leia_Organa
Leia_Organa

Reputation: 2104

Iterating through a array of hashes in Ruby (parsed JSON)

I have this array of hashes that was created when a did a API call and ran it through JSON.parse:

{
  "results": [
    {
      "zip": "08225",
      "city": "Northfield",
      "county": "Atlantic",
      "state": "NJ",
      "distance": "0.0"
    },
    {
      "zip": "08221",
      "city": "Linwood",
      "county": "Atlantic",
      "state": "NJ",
      "distance": "1.8"
    }
  ]
}

I am trying to get all the zipcodes out of each object and put them into an array:

zipcode_array = Array.new

I have tried the following code:

locations.each do |zipcode|
    zipcode_array.push(['results'][i]['zip'])
end

I would like my final output to be:

zipcode_array = ["08225", "08221"]

Anyone have any tips on what I'm missing?

Upvotes: 2

Views: 1624

Answers (2)

Rohit Lingayat
Rohit Lingayat

Reputation: 716

instead of using each you can use map function to achieve this.

response[:results].map{|x| x[:zip]}

This will give you the result in array i.e

["08225", "08221"]

Upvotes: 3

Igor Drozdov
Igor Drozdov

Reputation: 15075

Your code seems to lack i variable (index) here, but actually you don't need it, since you can always use map function to achieve idiomatic Ruby code:

require "json"

response = '{
  "results": [
    {
      "zip": "08225",
      "city": "Northfield",
      "county": "Atlantic",
      "state": "NJ",
      "distance": "0.0"
    },
    {
      "zip": "08221",
      "city": "Linwood",
      "county": "Atlantic",
      "state": "NJ",
      "distance": "1.8"
    }
  ]
}'

parsed_response = JSON.parse(response)
zipcode_array = parsed_response["results"].map { |address| address["zip"] }

Upvotes: 7

Related Questions