1

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?

1 Answer 1

1

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')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.