サブタイトル(検索用)
オブジェクトのコピーができない。
検証
スプレッド構文による代入
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() を使ってディープコピーしよう。
結論
ダディクール言いたかっただけ。