union of two objects javascript

Union of Two Objects in JavaScript

When working with JavaScript, you may encounter situations where you need to merge two objects into a single object. This process is called the union of two objects. There are several ways to accomplish this task, but we will explore two common methods:

Method 1: Using the Spread Operator

The spread operator is a new addition to JavaScript that allows you to expand an iterable object (such as an array or object) into individual elements. To use the spread operator to merge two objects, you can simply spread the properties of each object into a new object:


const obj1 = {
  name: 'John',
  age: 30
};

const obj2 = {
  address: '123 Main St',
  phone: '555-555-5555'
};

const union = { ...obj1, ...obj2 };

console.log(union);
// Output: { name: 'John', age: 30, address: '123 Main St', phone: '555-555-5555' }

In this example, we create two objects named obj1 and obj2. We then use the spread operator to merge the properties of both objects into a new object named union. The resulting object contains all of the properties from obj1 and obj2.

Method 2: Using Object.assign()

The Object.assign() method is another way to merge two objects in JavaScript. This method takes one or more source objects and copies their properties into a target object:


const obj1 = {
  name: 'John',
  age: 30
};

const obj2 = {
  address: '123 Main St',
  phone: '555-555-5555'
};

const union = Object.assign({}, obj1, obj2);

console.log(union);
// Output: { name: 'John', age: 30, address: '123 Main St', phone: '555-555-5555' }

In this example, we create two objects named obj1 and obj2. We then use the Object.assign() method to merge the properties of both objects into a new object named union. The first argument to Object.assign() is an empty object that serves as the target object. The remaining arguments are the source objects that we want to merge.

Both methods discussed above are valid ways to merge two objects in JavaScript. The choice of which to use depends on your personal preference and the requirements of your project.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe