How to Merge Objects in JavaScript?

Total
0
Shares

In this article, let us explore different ways to merge objects in JavaScript with examples. Merging objects is one of the most common scenario in JavaScript programming.

Merging objects refer to compiling them into a single new one. The properties of all the objects are combined.

There are mainly two methods of merging that we use in JavaScript.

  1. Shallow Merge
  2. Deep Merge

Merge Objects in JavaScript Using Shallow Merge

In the shallow merge, the properties possessed by the object are merged but will not incorporate the extended properties. In simple the properties of the first object are overwritten with the same property values of the second object.

The spread operator(...) and object.assign() uses the shallow merge method.

Let us look at each of these methods with examples

Method 1 : Merge objects using the spread operator (...)

We use the spread operator when all elements from an object need are contained in another object. The spread operator, written as ( . . . ) . We use it to merge objects with the properties of both retained.

Let us see this with an example.

let student = {
    fName: 'ABC',
    lName: 'XYZ',
    sAge: 25,
    rollNum: 'SU1234'
};

let school = {
    schoolName: 'Excel Academy',
    location: 'New York'
};

let Details = {
    ...student,
    ...school
};

console.log(Details);

Output

{
    location: "New York"
    fName: "ABC"
    lName: "XYZ"
    rollNum: "SU1234"
    sAge: 25
    schoolName: "Excel Academy"
}

In the case of the identical property name, the right-most object property replaces the last one. 

For Example

let student = {
    fName: 'ABC',
    lName: 'XYZ',
    sAge: 25,
    rollNum: 'SU1234',
    location: 'Washington DC'
};

let school = {
    schoolName: 'Excel Academy',
    location: 'New York'
};

let Details = {
    ...student,
    ...school
};

console.log(Details);

Output

{
    fName: "ABC"
    lName: "XYZ"
    location: "New York"
    rollNum: "SU1234"
    sAge: 25
    schoolName: "Excel Academy"
}

In the above example student and school objects has same property called location. When we merge both these object using the spread operator the location property from student is replaced with location property of school.

Method 2 : Merge objects using the Object.assign() method

This method replicates all enumerable properties from a source object to a target object. It will return the altered target object.

Syntax

Object.assign(targetObj, ...sourceObj)

Parameter(Required):

  • targetObj: Object returned after modification. 
  • sourceObj: Objects containing the properties.

Let us look how to merge objects using object.assign() method with an example.

let student = {
    fName: 'ABC',
    lName: 'XYZ',
    sAge: 25,
    rollNum: 'SU1234'
};

let school = {
    schoolName: 'Excel Academy',
    location: 'Washington DC'
};
let Details = Object.assign(student, school); 
console.log(Details);

Output

{
    fName: 'ABC',
    lName: 'XYZ',
    sAge: 25,
    rollNum: 'SU1234',
    schoolName: 'Excel Academy',
    location: 'Washington DC'
};

Merge Objects in JavaScript using Deep Merge

For merging first-level attributes we can use shallow merge. This is more simple approach. However if the object is complex and has many inner childrens or multiple levels then it is best to use Deep Merge. Deep merging assures that all levels of the objects are copied instead of referencing the original one. 

We accomplish this using the Lodash merge method.

The ‘_.merge() method merges objects from left to right. It produces a parent mapping object. When two keys are identical, the generated object will have the value of the right-most key. If multiple objects are the same, the newly created object will have only one key and value fitting those objects.

Syntax:

_.merge( objectName, sourceList )

Parameters:

  • objectName: This parameter contains the destination object.
  • sourceList: This parameter contains the source object. It is an optional parameter.

Let us understand with an example.

const _ = require('lodash')

const iceCream = {
  flavour: 'Vanilla',
  addOn: {
    sprinkler: 'yes',
    topping: 'chocoChip',
  },
}

const candy = {
  name: "Blackcurrent",
  category: 'candy',
  addOn: {
      sprinkler: 'yes',
    topping: 'None'
    },
}
const mergedValue= _.merge(iceCream, candy)

console.log(mergedValue)

Output

name: "Blackcurrent",
    addOn: {
        sprinkler: 'yes'
        ',
        topping: "None",
    },
    category: 'candy',
}

 We have created two objects with some common and some 

distinct properties. To combine them we are calling the _.merge() method. Merge takes the objects as parameters. It returns the combined object as output.

Conclusion

There are two primary ways to Merge Objects in JavaScript. The shallow merge is better for simple objects with only one level and deep merge works perfectly in case of multi-level/complex objects.

From the above examples we see that the deep merge is a better approach but only when we deal with complicated objects. Use this method if we have objects that have nested attributes. For simpler objects that do not have nested attributes, the shallow merge is preferable.

Leave a Reply

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

Sign Up for Our Newsletters

Get notified on the latest articles

You May Also Like
JavaScript String toUpperCase()

JavaScript String toUpperCase()

Table of Contents Hide toUpperCase() Example toUpperCase() SyntaxtoUpperCase() ParametertoUpperCase() Return Value Example: JavaScript Convert string from lowercase to uppercase In this tutorial, we will learn about the JavaScript String toUpperCase()…
View Post
JavaScript String endsWith()

JavaScript String endsWith()

Table of Contents Hide endsWith() SyntaxendsWith() ParametersendsWith() Return ValueJavaScript String endsWith() examplesJavaScript endsWith() example with length parameter In JavaScript, the endsWith() method determines whether the given string ends with a…
View Post
JavaScript Recursive Function

JavaScript Recursive Function

Table of Contents Hide Introduction to the JavaScript recursive functionsJavaScript recursive function examples1) A simple JavaScript recursive function example2) JavaScript Program to Find Factorial of Number Using RecursionWhy don’t we…
View Post