JavaScript Merge Objects

JavaScript Merge Objects | You will learn how to combine two or more JavaScript objects in this lesson to produce a new object with all the combined properties.

There are two ways to combine two items into a single new one that retains all of their properties:-

  • Employ a Spread Operator (…)
  • Implement the Object.assign() function

The spread operator, which may be used to merge two or more objects and generate a new one with the properties of the merged objects, was added in ES6.

JavaScript Merge Objects Using Spread Operator (…)

The person and Job objects are combined into the employee object in the following example using the spread operator(…):-

let person = {
  firstName: "John",
  lastName: "Doe",
  age: 25,
  ssn: "123-456-8754",
};

let job = {
  jobTitle: "JavaScript Developer",
  location: "USA",
};

let employee = {
  ...person,
  ...job,
};

console.log(employee);

Output:-

{
  firstName: 'John',
  lastName: 'Doe',
  age: 25,
  ssn: '123-456-8754',
  jobTitle: 'JavaScript Developer',
  location: 'USA'
}

If two objects have a property with the same name, the object property on the right replaces the earlier one. For instance:-

let job = {
  jobTitle: "JavaScript Developer",
  country: "USA",
};

let location = {
  city: "Paris",
  country: "France",
};

let remoteJob = {
  ...job,
  ...location,
};

console.log(remoteJob);

Output:-

{ jobTitle: ‘JavaScript Developer’, country: ‘France’, city: ‘Paris’ }

In this instance, the property country for the job and the location are the same. The result object (remoteJob) has the country property set to the value from the second object as a result of the merging of these objects (location).

JavaScript Merge Objects Using Object.assign()

You can copy all enumerable own properties from one or more source objects to a target object using the Object.assign() method, which returns the target object:- Object.assign(target, sourceObj1, sourceObj2, …);

Similar to the spread operator (…), the later object will replace the earlier object if the source objects share the same property name. See the example below:-

let person = {
  firstName: "John",
  lastName: "Doe",
  age: 25,
  ssn: "123-456-4741",
};

let job = {
  jobTitle: "JavaScript Developer",
  country: "USA",
};

let employee = Object.assign(person, job);
console.log(employee);

Output:-

{
  firstName: 'John',
  lastName: 'Doe',
  age: 25,
  ssn: '123-456-4741',
  jobTitle: 'JavaScript Developer',
  country: 'USA'
}

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *