To copy a map in JavaScript, you can use the Map constructor or the spread operator to create a new map with the same key-value pairs as the original map. These methods provide straightforward ways to duplicate a map.
We can copy a map in JavaScript using the Map constructor, which creates a new map with the same key-value pairs as the original map.
For example,
originalMap
with some key-value pairs. In this example, the map has string keys and integer values.Map
constructor to create a new map named copiedMap
that contains the same key-value pairs as originalMap
.console.log
function to verify the copy.const originalMap = new Map([
['one', 1],
['two', 2],
['three', 3]
]);
// Copy the map using the Map constructor
const copiedMap = new Map(originalMap);
// Print the copied map
console.log('Copied Map:', Array.from(copiedMap));
Copied Map: [['one', 1], ['two', 2], ['three', 3]]
We can also copy a map in JavaScript using the spread operator, which creates a new map with the same key-value pairs as the original map.
For example,
originalMap
with some key-value pairs. In this example, the map has string keys and integer values.copiedMap
that contains the same key-value pairs as originalMap
.console.log
function to verify the copy.const originalMap = new Map([
['one', 1],
['two', 2],
['three', 3]
]);
// Copy the map using the spread operator
const copiedMap = new Map([...originalMap]);
// Print the copied map
console.log('Copied Map:', Array.from(copiedMap));
Copied Map: [['one', 1], ['two', 2], ['three', 3]]
We can copy a map in JavaScript by using the forEach method to add all key-value pairs from the original map to a new map.
For example,
originalMap
with some key-value pairs. In this example, the map has string keys and integer values.copiedMap
.forEach
method to iterate over originalMap
and add each key-value pair to copiedMap
.console.log
function to verify the copy.const originalMap = new Map([
['one', 1],
['two', 2],
['three', 3]
]);
// Declare an empty map
const copiedMap = new Map();
// Copy the map using the forEach method
originalMap.forEach((value, key) => {
copiedMap.set(key, value);
});
// Print the copied map
console.log('Copied Map:', Array.from(copiedMap));
Copied Map: [['one', 1], ['two', 2], ['three', 3]]
In this tutorial, we learned How to Copy a Map in JavaScript language with well detailed examples.