javascriptecmascript-6

Shallow-clone a Map or Set


How do you shallow-clone a Map or Set object in JavaScript?

I want to get a new Map or Set that has the same keys and values.


Solution

  • Use the constructor to clone Maps and Sets:

    let clonedMap = new Map(originalMap);
    
    let clonedSet = new Set(originalSet);