How do I format an array of objects by iteration in Model in Ruby on Rails

I want to format an array of objects to send a substitution data in a Model. I would like to format that by iterating through a data called, "bags" and it's also an array of objects. For example,

bags = [{id: 1, name: "name1", product_id: 1}, {id: 2, name: "name2", product_id: 2"}]

The data "bags" has a relationship with "product" model so each bag has one product. I know I can get the "product" data by doing:

bags.map{|bag| bag.package}

However, I'm confused on how to use the result and re-format it as an array of object, since the result comes as an array.

I want to iterate through "bags" and use its relationship to get the "product" data to create an array of objects like this:

bag: 
   [
    {bag_name: "name1", product_name: "product1"}, 
    {bag_name: "name2", product_name: "product2"}
   ]

Please let me know if you need further information.

1 answer

  • answered 2020-06-27 05:46 Kyle-Law

    from what I'm understanding, you are trying to map bags into an array of object for each bag. Here is how I'd probably do with the information you've given:

    bags.map do |bag|
      {bag_name: bag[:name], product_name: bag.package}
    end
    

    In this function, bag[:name] return the name properties of each bag, whereas bag.package returns the product "data" you mentioned. It map through the bags array and output an array of objects using map method.

    Feel free to give it a try and update here if there's any further errors/problems.

    Cheers :)