Search code examples
ruby-on-railsrubyruby-on-rails-5

Merge object and add keys from JSON format using Ruby on Rails


I have a list of array that is queried that needs to be merged with the same location_id based on the objects.

**this are the code for generating array **

       filled  =  Product.on_hand_location(pid).to_a
       empty   =  Product.on_hand_location_empty_cylinder(pid).to_a
       data    = filled + empty 
  
 
       result = data.map{ |k| 
        { 
        details: { 
              location_id: k['location_id'],
              "location_name"=>k['location_name'],
              "onhandcylynder"=>k['onhand'] == nil ?  0 :  k['onhand'],
              "emptycylynder"=> k['emptyonhand'] == nil ?  0 :  k['emptyonhand']
           } ,
        }
     }
    
    respond_with [ onhand: result ]

This JSON format below is the output of code above. which has location_id that needs to be merge

[{
    "onhand": [{
            "details": {
                "location_id": 1,
                "location_name": "Capitol Drive",
                "onhandcylynder": "4.0",
                "emptycylynder": 0
            }
        },
        {
            "details": {
                "location_id": 2,
                "location_name": "SM City Butuan",
                "onhandcylynder": "5.0",
                "emptycylynder": 0
            }
        },
        {
            "details": {
                "location_id": 1,
                "location_name": null,
                "onhandcylynder": 0,
                "emptycylynder": "2.0"
            }
        }
    ]
  }]

My desired output

  [{
     "onhand": [{
        "details": {
            "location_id": 1,
            "location_name": "Capitol Drive",
            "onhandcylynder": "4.0",
            "emptycylynder": 0
        }
    },
    {
        "details": {
            "location_id": 2,
            "location_name": "SM City Butuan",
            "onhandcylynder": "5.0",
            "emptycylynder": "2.0"
        }
    }
   ]
 }]

Solution

  • I refactor my code and able to get my desired result

      filled  =  Product.on_hand_location(pid).to_a
      emptyTank =  Product.on_hand_location_empty_cylinder(pid).to_a
      data = filled + emptyTank 
      
      cylinder = data.map(&:dup)
      .group_by { |e| e.delete('location_id') }
    
       finalResult = cylinder.map{|_, location_id | location_id.reduce({}) { |result, location_id|
         result.merge(location_id)
      } }
    
      respond_with [ onhand: finalResult]
    

    The result already merge with the same location id and emptyonhand keys are merge already in corresponding to its location ID

    [
    {
        "onhand": [
            {
                "onhand": "1.0",
                "location_name": "Capitol Drive",
                "emptyonhand": "5.0"
            },
            {
                "onhand": "5.0",
                "location_name": "SM City Butuan"
            }
        ]
    }
    

    ]