Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform array of objects in Ruby

Tags:

json

arrays

ruby

I have JSON with one object for each site's traffic for 3 dates.

I want to merge these three objects together on "Date". Example below.

I'm using Ruby. What is the easiest way to do this?

Start JSON:

 [  
   {  
      "Google":[  
         {  
            "Date":"2015-01-01",
            "Value":100
         },
         {  
            "Date":"2015-02-01",
            "Value":200
         },
         {  
            "Date":"2015-03-01",
            "Value":300
         }
      ]
   },
   {  
      "Yahoo":[  
         {  
            "Date":"2015-01-01",
            "Value":1200
         },
         {  
            "Date":"2015-02-01",
            "Value":1300
         },
         {  
            "Date":"2015-03-01",
            "Value":1400
         }
      ]
   },
   {  
      "Bing":[  
         {  
            "Date":"2015-01-01",
            "Value":500
         },
         {  
            "Date":"2015-02-01",
            "Value":600
         },
         {  
            "Date":"2015-03-01",
            "Value":700
         }
      ]
   }
]

End JSON:

[
  {  
    "Date":"2015-01-01",
    "Google":100,
    "Yahoo":1200,
    "Bing":500
  },
  {  
    "Date":"2015-01-02",
    "Google":200,
    "Yahoo":1200,
    "Bing":600
  },
  {  
    "Date":"2015-01-03",
    "Google":300,
    "Yahoo":1400,
    "Bing":700
  }
]
like image 464
Don P Avatar asked Oct 15 '25 04:10

Don P


1 Answers

result = array.inject({}) do | a, e | 
  site, data = e.first
  data.each do | x | 
    a[x[:Date]] ||= {}
    a[x[:Date]][site] = x[:Value]
  end
  a
end

gives you a hash with the dates as keys. This can be transformed to the array by:

result.map { | k, v | v.update(:Date => k) }
like image 125
undur_gongor Avatar answered Oct 17 '25 20:10

undur_gongor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!