Edit : Question marked as duplicate, but the duplicated post is not helping me fixing this issue. How can I modify the value of the map2 without changing the one from map1 ? ( Is JavaScript a pass-by-reference or pass-by-value language? )
I have 2 maps. The first one can be considered as a "Source of truth" that is initialized at loading of the page. I want to duplicate the content of the first map into a second one. So all my changes will be applied to the second map, and I will use my first one if I want to revert my changes.
But duplicating a map is the cause of a weird bug that change the content of the first map when the second one is changed.
var map1 = new Map()
var map2 = new Map()
map1.set('1', 'one')
map1.set('2', {alpha:"NOT",beta:"MODIFIED"})
map1.set('3', 'three')
// Duplicate the content of the first map into the second one //
map2 = new Map(map1) //<-- this is probably because of that assignment
var x = map2.get('2')
x.alpha = "why???"
x.beta = "how???"
//Why does the value of the map change when I edit the 'x' variable ?
// map2.set('2', x); is not required ?
console.log("MAP1 : " + JSON.stringify(map1.get('2')))
console.log("MAP2 : " + JSON.stringify(map2.get('2')))
But the snippet blow work well and won't modify the value of the first map (but I can't modify only a part of the content inside map2 with this method)
var map1 = new Map()
var map2 = new Map()
map1.set('1', 'one')
map1.set('2', {alpha:"NOT",beta:"MODIFIED"})
map1.set('3', 'three')
// Duplicate the content of the first map into the second one //
map2 = new Map(map1) //<-- this is probably because of that assignment
map2.set('2', {alpha:'but this', beta:'work ???'})
console.log("MAP1 : " + JSON.stringify(map1.get('2')))
console.log("MAP2 : " + JSON.stringify(map2.get('2')))
What is happening ?