1

So from the title itself. I have an initialize object like say

"travellerDetails": { 
       "traveller_1": { 
              "Full Name": "", 
              "Gender": "", 
    }, "traveller_2": { 
             "Full Name": "", 
             "Gender": "",
    }, "traveller_3": { 
              "Full Name": "", 
              "Gender": ""
    } 
}

However, when I load my data object from an Ajax call

"travellerDetails": { 
           "traveller_1": { 
                  "Full Name": "John Doe", 
                  "Gender": "M", 
        }, "traveller_2": { 
                 "Full Name": "Jane Doe", 
                 "Gender": "F",
        }
    }, 

I get an error when I try to store the loaded data to an initialize object.

bookingForm.travellerDetails = data.travellerDetails;

I was expecting that traveller_3 will be set as "" considering that I only have 2 travellers when loaded. But when the initialize object is the same size as the one I loaded from an ajax call my code runs perfectly. So how do I copy the loaded object to the initialize one with different sizes?

Thanks!

drake24
  • 525
  • 1
  • 11
  • 32

1 Answers1

2

You can use the es6 Object Spread Operator.

Try this:

bookingForm.travellerDetails = { ...bookingForm.travellerDetails, ...data.travellerDetails};

This essentially means: make a new object with bookingForm.travellerDetails's original properties, and override all the common properties between bookingForm.travellerDetails and data.travellerDetails with the data from the latter, plus add additional properties from data.travellerDetails if there are any. All the properties which are found in bookingForm but not in data will have the same values as in bookingForm.

Note that this is es6 only syntax, if you use babel you'll need this plugin.

Gibor
  • 1,695
  • 6
  • 20