Skip to content
Related Articles

Related Articles

ES6 | Merge Objects
  • Last Updated : 22 Nov, 2019

We can merge two JavaScript Objects in ES6 by using the two popular methods. The methods are listed below:

  • Object.assign() method
  • Object spread syntax method

Both the methods are described below with the proper example:

Method 1: To marge two object we will use Object.assign() method.

  • Syntax:
    Object.assign(target, ...sources)
  • Example:




    <script> 
      
        // An Object
        var obj1 = {1 : "Geeks", 2: "for"};
        var obj2 = { 3 : "Geeks"};
          
        // Using Object.assign()
        Object.assign(obj1, obj2);
          
        // Printing object
        for (var key of Object.keys(obj1)) {
            document.write(key + " => " + obj1[key] + "</br>")
        }
    </script> 
  • Output:
    1 => Geeks
    2 => for
    3 => Geeks
    

Method 2: In this method, to marge two object we will use Object spread syntax.

  • Syntax:
    var objClone = { ...obj };
  • Example:




    <script> 
      
        // An Object
        var obj1 = {1 : "Geeks", 2: "for"};
        var obj2 = { 3 : "Geeks"};
          
        // Using Object spread syntax
        var obj = {...obj1, ...obj2};
          
        // Printing object
        for (var key of Object.keys(obj)) {
            document.write(key + " => " + obj[key] + "</br>")
        }
    </script> 
  • Output:
    1 => Geeks
    2 => for
    3 => Geeks



My Personal Notes arrow_drop_up
Recommended Articles
Page :