Categories
JavaScript Answers

How to Clone a Map or Set in JavaScript?

Spread the love

Sometimes, we want to clone a map or set in JavaScript.

In this article, we’ll look at how to clone a map or set in JavaScript.

Shallow Clone a Map or Set in JavaScript

To shallow clone a map or a set, we can just pass in the original map or set into the Map or Set constructor respectively.

For instance, we can write:

const originalMap = new Map([
  ['foo', 1],
  ['bar', 2]
])
const clonedMap = new Map(originalMap)

const originalSet = new Set([1, 2, 3])
const clonedSet = new Set(originalSet)

We create the originalMap and originalSet which we want to shallow clone.

To do that, we just pass them into the Map and Set constructors respectively.

Deep Clone a Map or Set in JavaScript

To shallow clone a map or a set, we can just pass in the original map or set that has been stringified into JSON and parsed back into arrays into the Map or Set constructor respectively.

For instance, we can write:

const originalMap = new Map([
  ['foo', 1],
  ['bar', 2]
])
const deepClonedMap = new Map(JSON.parse(JSON.stringify([...originalMap])))

const originalSet = new Set([1, 2, 3])
const deepClonedSet = new Set(JSON.parse(JSON.stringify([...originalSet])))

To spread the originalMap and originalSet into arrays. Then we call JSON.stringify to convert the arrays into JSON strings.

And then we call JSON.parse to parse the JSON strings back to arrays.

Then finally, we pass them back into the Map or Set constructors to create new maps or sets from them.

Conclusion

To shallow clone a map or a set, we can just pass in the original map or set into the Map or Set constructor respectively.

To shallow clone a map or a set, we can just pass in the original map or set that has been stringified into JSON and parsed back into arrays into the Map or Set constructor respectively.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *