0

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
dwjohnston
  • 11,163
  • 32
  • 99
  • 194
tmp dev
  • 8,043
  • 16
  • 53
  • 108
  • 1
    So, `const mergedObject = object1.customerId ? {...object1, ...object2} : {...object2, ...object1};`? – Bergi Dec 19 '18 at 06:47

1 Answers1

1
let mergedObject;

if (object1.customerId) {
    // Consider that even if both have customerId object1 override object2
    // You might want to check if (object1.customerId && !object2.customerId)
    mergedObject = {...object2, ...object1}
}
else {
    // Event if both have customerId object 2 will override object 1
    mergedObject = {...object1, ...object2}
}



// or with Ternary:
let mergedObject = object1.customerId ? {...object2, ...object1} : {...object1, ...object2}
amirhaa
  • 280
  • 1
  • 8