1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

スプレッド構文も分割代入もMap.set()もシャローコピーだってよ

Last updated at Posted at 2023-07-04

サブタイトル(検索用)

オブジェクトのコピーができない。

検証

スプレッド構文による代入

1階層目のみコピーされる。コピー元オブジェクトも削除されない。

const family = { parents: { father: "dad", mother: "mom" }, child: "kid" };
const newFamily = { ...family };

console.log(family); // Old family exists.

family.child = "youth";
console.log(newFamily.child); // still kid

family.parents.father = "daddy";
console.log(newFamily.parents.father); // daddy cool!

分割代入による代入

こちらも1階層目のみコピーされる。コピー元オブジェクトは削除されない。
ネストされた値を直接指定して代入すれば別の値としてコピーできる。

const family = { parents: { father: "dad", mother: "mom" }, child: "kid" };
const { parents, child } = family;
const { father } = family.parents; // Only parents ok.

console.log(family); // Family is not destroyed.

family.child = "youth"
console.log(child); // still kid

family.parents.father = "daddy"
console.log(father) // Oh dad...
console.log(parents.father) // daddy cool!

Map.set()による代入

これもシャローコピーとなる。1階層目より下は元のオブジェクトを参照する。

const family = { parents: { father: "dad", mother: "mom" }, child: "kid" };

const familyMap = new Map()
familyMap.set("member",{...family})
console.log(familyMap.get("member")) // dad, mom, kid

family.child = "youth"
console.log(familyMap.get("member").child) // still kid

family.parents.father = "daddy"
console.log(familyMap.get("member").parents.father) // daddy cool!

解決策

structuredClone() を使ってディープコピーしよう。

結論

ダディクール言いたかっただけ。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?