AutoVit
AutoVit

Reputation: 83

How can I iterate over an array of hashes and form new one

I have a call to Companies House API and response I get from API is an array of hashes.

companies = {
 "total_results" => 2, 
 "items" => [{
  "title" => "First company",
  "date_of_creation" => "2016-11-09",
  "company_type" => "ltd",
  "company_number" => "10471071323",
  "company_status" => "active"
 }, 
 {
  "title" => "Second company",
  "date_of_creation" => "2016-11-09",
  "company_type" => "ltd",
  "company_number" => "1047107132",
  "company_status" => "active"
 }]
}

How I can iterate over companies and get a result similar to:

[{
  title: "First company",
  company_number: "10471071323"
},
{
  title: "Second company",
  company_number: "1047107132"
}]

Upvotes: 1

Views: 164

Answers (3)

Tom Harvey
Tom Harvey

Reputation: 4332

The answers are totally correct; but you should be made aware that what you’re looking at from companies house is not just an array of hashes - it’s a valid JsonApi response.

You might find your job easier if you’re using a gem which is aware of JsonApi specs, or if you’re just approaching it as that kind of data.

Have a look at the ruby implementations of https://jsonapi.org/implementations/

Or ActiveModelSerializer for ways to not only reform your hashes but deserialise this very structured data into ruby objects.

But like I say, if all you’re looking for is a quick way to reform the data as you describe. The above answers are perfect.

Upvotes: 0

Clemens Kofler
Clemens Kofler

Reputation: 1968

companies.map { |company| company.slice('title', 'company_number').symbolize_keys }

This should do the trick.

If you're not using Rails (or, more specifically, ActiveSupport), then symbolize_keys won't be available. In this case, you'd have to go for a more standard-Ruby approach:

companies.map do |company|
  { title: company["title"], company_number: company["company_number"] }
end

Upvotes: 0

Fernando Briano
Fernando Briano

Reputation: 7757

You can use map which will iterate through the elements in an array and return a new array:

companies["items"].map do |c| 
  {
    title: c['title'],
    company_number: c['company_number'] 
  }
end
 => [
  {:title=>"First company", :company_number=>"10471071323"},
  {:title=>"Second company", :company_number=>"1047107132"}
] 

Upvotes: 1

Related Questions