merging & cloning JavaScript objects using Object.assign()

merging JavaScript objects using Object.assign()

 var obj1 = { a1: ["a", "b", "c"] };  
 var obj2 = { a1: ["d", "e"],  
        a2: ["f", "g", "h"] };  
 var result = Object.assign({}, obj1, obj2);  
 console.log(JSON.stringify(result, null, 2));  

output:

{
  "a1": [
    "d",
    "e"
  ],
  "a2": [
    "f",
    "g",
    "h"
  ]
}


__________________
more details on Object.assign():
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

__________________
Object.assign() can also be used to shallow clone an object:


 var clone = Object.assign(obj1);  

Comments