jose miliano
jose miliano

Reputation: 73

how to create an array of hashes by looping over array of objects

I have following array of hash. I am trying to loop over it and build an array of hash of values of id and product_order_id.

objects = 
[
  #<Product: 0x00007ffd4a561108
  @id="1",
  @product_id="2",
  @product_order_id="23",
  @description="abc",
  @status="abcde",
  @start_date=nil,
  @end_date=nil>,
  #<Product: 0x00007ffd4a560c80
  @id="45",
  @product_id="22",
  @product_order_id="87",
  @description="ahef",
  @status="gesff",
  @start_date=nil,
  @end_date=nil>
......more objects.....
    ]

This is what it should look like

[{ "1": "23" }, { "45": "87" }] -->its going to be uuid

I tried doing this but no luck

def mapped_product(objects)
    mapping = []
    objects.each do |object|
      mapping << {
        object.product_order_id: object.id
      }
    end
end

Any idea?

Upvotes: 0

Views: 91

Answers (3)

Mereghost
Mereghost

Reputation: 688

I'd usually implement it using an each_with_object

objects.each_with_object({}) { |obj, acc| acc[obj.id] = obj.product_order_id }

Unless I reaaaly want to squeeze some performance, than I'd go with Gagan's answer

Upvotes: 1

Gagan Gami
Gagan Gami

Reputation: 10251

inline solution:

> Hash[objects.map{|p| [p.id, p.product_order_id] }]
# Output : [{ 1=>23 }, { 45=>87 }]

Upvotes: 1

nicosantangelo
nicosantangelo

Reputation: 13716

Have you tried this?

def mapped_product(objects)
    mapping = []
    objects.each do |object|
      mapping << {
        object.id => object.product_order_id # I'm using an `=>` here
      }
    end
    mapping # return the new mapping
end

I've just changed the : on the hash for a => to "make it dynamic" and swapped the values of id and product_order_id

You can also use a map here:

def mapped_product(objects)
    objects.map do |object|
     {  object.id => object.product_order_id }
    end
end

Upvotes: 0

Related Questions