Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

ES6 | Merge Objects

  • Last Updated : 12 Oct, 2021

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 merge two object we will use Object.assign() method. 
 

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

javascript




<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 merge two object we will use Object spread syntax
 

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

javascript




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

Start Your Coding Journey Now!