0

Suppose we have objects as map values and we want to deep clone the map. What is the proper way to do it?

rebinnaf
  • 276
  • 2
  • 9

1 Answers1

-2

Edit: If the values are not set or map this will work.

Deep clone:

var deepClonedMap = new Map(JSON.parse(JSON.stringify([...originalMap])))
var deepClonedSet = new Set(JSON.parse(JSON.stringify([...originalSet])))

let originalMap = new Map()
let data = {a:'a',b:'b'}
originalMap.set(1,data)

let shallowCloned = new Map(originalMap)
let deepCloned = new Map(JSON.parse(JSON.stringify([...originalMap])))
data.a = 'p'
console.log('originalMap:',[...originalMap])
console.log('shallowCloned:',[...shallowCloned])
console.log('deepCloned:',[...deepCloned])
rebinnaf
  • 276
  • 2
  • 9
  • 1
    Have you tested this with something like `originalMap.set(2,new Set([1,2,3,4]))`? – georg May 03 '21 at 15:39
  • 1
    Won't this break if the original map or set has circular references (i.e. some entry contains within it a reference back to the original set or map)? – Seth Lutske May 03 '21 at 15:39
  • you are right, this works only if values are not set or map themselves. – rebinnaf Aug 26 '21 at 07:27