1

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" }] 
1

3 Answers 3

1

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"} ] 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Fernando, this worked out for me. I have as well added #dig method to avoid NoMethodError: undefined method '[]' for nil:NilClass
0
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 

3 Comments

slice keeps the string keys.
Fair enough. If Rails is being used, you can add symbolize_keys: companies.map { |company| company.slice('title', 'company_number').symbolize_keys }
@ClemensKofler: It may be useful to update your original answer to include that alternate option, and a better explanation of when one is useful compared to the others.
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.