User140827
User140827

Reputation: 19

Combine Multiple Arrays + Variable into single JSON object

I want combine two arrays and two constant values to an single json object.

my Arrays:
arraywithperson=[Alfredo, James, John, Sarah, Vladimir ]

arraywithduration=[1,5,3,1,4]

variables:
start_date = Date.today

parent = 1

My Json Output should be:
    {"data": [
           {"person": "Alfredo", "start_date" = 22.01.2020, "duration": 1, "parent": "1"}
           {"person": "James", "start_date" = 22.01.2020, "duration": 5, "parent": "1"}
           {"person": "John", "start_date" = 22.01.2020, "duration": 3, "parent": "1"}
           {"person": "Sarah", "start_date" = 22.01.2020, "duration": 1, "parent": "1"}
           {"person": "Vladimir", "start_date" = 22.01.2020, "duration": 4, "parent": "1"}
           ]}

How can i combine the arrays with my variables that i can get this json output?

Upvotes: 1

Views: 176

Answers (1)

Sebastián Palma
Sebastián Palma

Reputation: 33420

You can use zip and map for that:

output = arraywithduration.zip(arraywithperson).map do |duration, person|
           {
             'person': person,
             'start_date': start_date,
             'duration': duration,
             'parent': parent
           }
         end
{ 'data': output }

With zip you can merge the elements of arraywithduration and the elements of arraywithperson into an array of 2 elements, inside a "main" array:

# [[1, "Alfredo"], [5, "James"], [3, "John"], [1, "Sarah"], [4, "Vladimir"]]

And map allows you to iterate over each element and create a hash with the keys and values you need:

# [{:person=>"Alfredo",  :start_date=>"22.01.2020", :duration=>1, :parent=>1},         
#  {:person=>"James",    :start_date=>"22.01.2020", :duration=>5, :parent=>1}, 
#  {:person=>"John",     :start_date=>"22.01.2020", :duration=>3, :parent=>1}, 
#  {:person=>"Sarah",    :start_date=>"22.01.2020", :duration=>1, :parent=>1}, 
#  {:person=>"Vladimir", :start_date=>"22.01.2020", :duration=>4, :parent=>1}]

To get the start_date as you show in your expected output you can use strftime (it's a String BTW):

start_date = Date.today.strftime('%d.%m.%Y')

Upvotes: 1

Related Questions