Merge Properties of Two Objects Dynamically in JavaScript

Introduction

In JavaScript, an object is defined as a collection of key-value pairs. An object is also a non-primitive data type.

You'll oftentimes need to combine objects into a single one which contains all the individual properties of its constituent parts. This operation is called merging. The two most common ways of doing this are:

  • Using the spread operator (...)
  • Using the Object.assign() method

In this tutorial, we'll take a look at how to merge two objects dynamically in JavaScript.

After that, we'll cover the difference between shallow merge and deep merge, because it is essential to fully understanding object merging.

Merge JavaScript Objects Using the Spread Operator

We can merge different objects into one using the spread operator (...). This is also the most common method of merging two or more objects.

This is an immutable approach to merging two objects, i.e., the starting two objects which are used to make the merged one are not changed in any way due to side effects. In the end, you've got a new object, constructed from the two, while they're still intact.

Let's create two objects and merge them:

const person = {
    name: "John Doe",
    age: 24
}
const job = {
    title: "Full stack developer",
    location: "Remote"
}

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

console.log(employee);

This results in:

{
    name: "John Doe", 
    age: 24, 
    title: "Full stack developer", 
    location: "Remote"
}

Note: If there are common properties between these two objects, such as both of them having a location, the properties from the second object (job) will overwrite the properties of the first object (person):

const person = {
    name: "John Doe",
    location: "Remote"
}
const job = {
    title: "Full stack developer",
    location: "Office"
}
const employee = {...person, ...job}

console.log(employee);

This results in:

{
  name: 'John Doe',
  location: 'Office',
  title: 'Full stack developer'
}

If more than two objects are being merged, the rightmost object overrides the ones to the left.

Merge JavaScript Objects Using Object.assign()

Another common way to merge two or more objects is to use the built-in Object.assign() method:

Object.assign(target, source1, source2, ...);

This method copies all the properties from one or more source objects into the target object. Just like with the spread operator, while overwriting, the right-most value is used:

const person = {
    name: "John Doe", 
    age: 24,
    location: "U.S.A"
}
const job = {
    title: "Full stack developer",
    location: "Remote"
}

const employee = Object.assign(person, job);

console.log(employee);

Running the code above will result in the following output:

{
    name: "John Doe", 
    age: 24,
    location: "Remote",
    title: "Full stack developer"
}

Again, keep in mind that the object referenced by employee is a completely new object, and is in no way linked to the objects referenced by person or job.

Shallow Merge vs Deep Merge

In the case of a shallow merge, if one of the properties on a source object is another object, the target object contains the reference to the same object that exists in the source object. A new object is not created in this case.

Let's tweak the previous person object, and make location an object for itself:

const person = {
    name: "John Doe",
    location: {
        city: "London", 
        country: "England"
    }
}
const job = {
    title: "Full stack developer"
}

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

console.log(employee.location === person.location);

This results in:

true

We can see that the reference to the location object in both person and employee object is the same. In fact, both the spread operator (...) and Object.assign() perform a shallow merge.

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

JavaScript has no deep merge support out of the box. However, there are third-party modules and libraries which do support it, like Lodash's _.merge.

Conclusion

In this tutorial, we've taken a look at how to merge two objects in JavaScript. We've explored the spread operator (...) and the Object.assign() method, which both perform a shallow merge of two or more objects, into a new one, without affecting the constituent parts.

Introduction

In JavaScript, an object is defined as a collection of key-value pairs. An object is also a non-primitive data type.

You'll oftentimes need to combine objects into a single one which contains all the individual properties of its constituent parts. This operation is called merging. The two most common ways of doing this are:

  • Using the spread operator (...)
  • Using the Object.assign() method

In this tutorial, we'll take a look at how to merge two objects dynamically in JavaScript.

After that, we'll cover the difference between shallow merge and deep merge, because it is essential to fully understanding object merging.

Merge JavaScript Objects Using the Spread Operator

We can merge different objects into one using the spread operator (...). This is also the most common method of merging two or more objects.

This is an immutable approach to merging two objects, i.e., the starting two objects which are used to make the merged one are not changed in any way due to side effects. In the end, you've got a new object, constructed from the two, while they're still intact.

Let's create two objects and merge them:

const person = {
    name: "John Doe",
    age: 24
}
const job = {
    title: "Full stack developer",
    location: "Remote"
}

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

console.log(employee);

This results in:

{
    name: "John Doe", 
    age: 24, 
    title: "Full stack developer", 
    location: "Remote"
}

Note: If there are common properties between these two objects, such as both of them having a location, the properties from the second object (job) will overwrite the properties of the first object (person):

const person = {
    name: "John Doe",
    location: "Remote"
}
const job = {
    title: "Full stack developer",
    location: "Office"
}
const employee = {...person, ...job}

console.log(employee);

This results in:

{
  name: 'John Doe',
  location: 'Office',
  title: 'Full stack developer'
}

If more than two objects are being merged, the rightmost object overrides the ones to the left.

Merge JavaScript Objects Using Object.assign()

Another common way to merge two or more objects is to use the built-in Object.assign() method:

Object.assign(target, source1, source2, ...);

This method copies all the properties from one or more source objects into the target object. Just like with the spread operator, while overwriting, the right-most value is used:

const person = {
    name: "John Doe", 
    age: 24,
    location: "U.S.A"
}
const job = {
    title: "Full stack developer",
    location: "Remote"
}

const employee = Object.assign(person, job);

console.log(employee);

Running the code above will result in the following output:

{
    name: "John Doe", 
    age: 24,
    location: "Remote",
    title: "Full stack developer"
}

Again, keep in mind that the object referenced by employee is a completely new object, and is in no way linked to the objects referenced by person or job.

Shallow Merge vs Deep Merge

In the case of a shallow merge, if one of the properties on a source object is another object, the target object contains the reference to the same object that exists in the source object. A new object is not created in this case.

Let's tweak the previous person object, and make location an object for itself:

const person = {
    name: "John Doe",
    location: {
        city: "London", 
        country: "England"
    }
}
const job = {
    title: "Full stack developer"
}

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

console.log(employee.location === person.location);

This results in:

true

We can see that the reference to the location object in both person and employee object is the same. In fact, both the spread operator (...) and Object.assign() perform a shallow merge.

JavaScript has no deep merge support out of the box. However, there are third-party modules and libraries which do support it, like Lodash's _.merge.

Conclusion

In this tutorial, we've taken a look at how to merge two objects in JavaScript. We've explored the spread operator (...) and the Object.assign() method, which both perform a shallow merge of two or more objects, into a new one, without affecting the constituent parts.

Last Updated: October 4th, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Abhilash KakumanuAuthor

Hey, I am a full-stack web developer located in India. I am a curious person who is always trying to wrap my head around new technologies. In my free time, I read novels and play with my dog!

Project

React State Management with Redux and Redux-Toolkit

# javascript# React

Coordinating state and keeping components in sync can be tricky. If components rely on the same data but do not communicate with each other when...

David Landup
Uchechukwu Azubuko
Details

Getting Started with AWS in Node.js

Build the foundation you'll need to provision, deploy, and run Node.js applications in the AWS cloud. Learn Lambda, EC2, S3, SQS, and more!

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms