Write a JavaScript Program to Merge Property of Two Objects

Merging properties of two objects in JavaScript is a common task that programmers often encounter.

Luckily, JavaScript provides a simple way to merge the properties of two objects using the Object.assign() method.

The Object.assign() method is used to copy the values of all enumerable properties from one or more source objects to a target object.

It takes the target object as its first argument and one or more source objects as its subsequent arguments.

The properties of the source objects are then copied over to the target object.

Here’s an example:

const obj1 = {a: 1, b: 2};
const obj2 = {c: 3, d: 4};
const mergedObj = Object.assign({}, obj1, obj2);

console.log(mergedObj); // {a: 1, b: 2, c: 3, d: 4}

In this example, we create two objects obj1 and obj2 with properties a, b, c, and d.

We then use the Object.assign() method to merge the properties of obj1 and obj2 into a new object called mergedObj.

We pass an empty object {} as the first argument to the Object.assign() method.

This empty object serves as the target object, which will contain the merged properties of obj1 and obj2. We then pass obj1 and obj2 as subsequent arguments to the Object.assign() method.

The result is a new object mergedObj with properties a, b, c, and d.

In conclusion, merging properties of two objects in JavaScript is a simple task using the Object.assign() method.