Lets say I have the following two objects
object1: {
CustomerId: 1,
CustomerData: [1,2,3,4]
}
object2: {
CustomerId: 2,
CustomerData: [11,22,33,44]
CustomerOrders: [5,6,7,8]
}
Now I need to merge the two objects using the following business logic
If either object contains a CustomerId then that should override the properties of the other object. For example if the two objects were
object1: {
CustomerId: 1,
CustomerData: [1,2,3,4]
}
object2: {
CustomerData: [11,22,33,44]
CustomerOrders: [5,6,7,8]
}
Since object2 does not contain CustomerId the final merged object should be as follows
mergedObject: {
CustomerId: 1,
CustomerData: [1,2,3,4],
CustomerOrders: [5,6,7,8]
}
Note* I have preserved the CustomerData of object1 and not object2 since object2 lacks customerId.
I am looking to use the ES6 spread operator to achieve this. So I will use something like this
const mergedObject = {...val1, ...val2}
My problem is that what comes first in the {} is determined as to which object contains the customerId. There at the moment I have an if condition which checks if customerId is found in the object and then assign to object2 since that will override the other. so I have something like this
if (object1.customerId){
val2 = object1;
val1 = object2;
} else if (object2.customerId){
val2 = object2;
val1 = object1;
}
This is very long and in my opinion ugly, is there a better way I can do this in the spread/constructor operator itself?
const mergedObject = {...val1, ...val2} //Do it here itself