One effective method to combine object properties in JavaScript is by using Object.assign()
. This function copies all enumerable own properties from one or more source objects into a target object and returns the updated target object.
When using Object.assign()
, it merges values of multiple objects while prioritizing the source object's properties over the target object's. For more information, refer to this MDN link.
Here is an example illustrating how Object.assign()
can be utilized:
let data1 = await this.processResponse(__data.Details[0]); //Assuming the promise resolves to {foo: 4, bar: 49}
console.log("firstCallData" , data1);
let data2 = await this.orderResponse(__data.Details[1]); //Assuming this promise resolves to {baz: 69, bar: 42}
data = Object.assign(data2, data1);
console.log("DATA", data);
return Promise.resolve(data);
By executing the above code snippet, the resultant merged object would be:
{foo: 4, bar: 49, baz: 69}
Note that when there are overlapping properties between the source and target objects, Object.assign()
will prioritize the source object's properties.