如何在 JavaScript 中创建地图的深层副本

在 JavaScript 中创建地图的深层副本

How to create a Deep Copy of a Map in JavaScript

创建 a 的深拷贝Map

  1. 将 转换Map为数组。
  2. 使用JSON.stringify()方法对数组进行字符串化。
  3. 使用JSON.parse()方法解析 JSON。
  4. 将结果传递给Map()构造函数。
索引.js
const existingMap = new Map([ ['address', {street: 'Example'}], ['numbers', [1, 2, 3]], ]); const deepCopy = new Map(JSON.parse( JSON.stringify(Array.from(existingMap)) )); // 👇️ {'address' => {street: 'Example'}, 'numbers': [1, 2, 3]} console.log(deepCopy);

我们使用
Array.from
方法将 转换
Map为二维数组。

索引.js
const existingMap = new Map([ ['address', {street: 'Example'}], ['numbers', [1, 2, 3]], ]); // 👇️ [['address', {street: 'Example}], ['numbers', [1, 2, 3]]] console.log(Array.from(existingMap));

下一步是使用
JSON.stringify
方法将数组转换为 JSON 字符串。

这使得所有嵌套的数组和对象都失去了它们的引用。

We then used the
JSON.parse
method to parse the string back into an array.

The last step is to pass the two-dimensional array to the
Map()
constructor.

The trick here is to stringify the array, using the JSON.stringify method, so that all nested objects lose their reference.

If we then try to mutate the array in the new Map, it wouldn’t affect the
existing Map.

index.js
const existingMap = new Map([ ['address', {street: 'Example'}], ['numbers', [1, 2, 3]], ]); const deepCopy = new Map(JSON.parse( JSON.stringify(Array.from(existingMap)) )); deepCopy.get('numbers').pop(); // 👇️ {'address' => {street: 'Example'}, 'numbers' => [1, 2]} console.log(deepCopy); // 👇️ {'address' => {'street':'Example'},'numbers' => [1, 2, 3]} console.log(existingMap);

We used the pop method to mutate the array in the deep copy, however the array
in the existing Map wasn’t affected.

The nested arrays in the Maps have a different reference and location in memory
because we used the JSON.stringify method.