ES6 | Merge Objects

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:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <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> 

    chevron_right

    
    

  • 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:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <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> 

    chevron_right

    
    

  • Output:
    1 => Geeks
    2 => for
    3 => Geeks

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.